栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java8的蛋糕模式可能吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java8的蛋糕模式可能吗?

从其他答案中得到启发,我想到了以下(粗糙的)类层次结构,该层次结构类似于Scala中的蛋糕模式:

interface UserRepository {    String authenticate(String username, String password);}interface UserRepositoryComponent {    UserRepository getUserRepository();}interface UserServiceComponent extends UserRepositoryComponent {    default UserService getUserService() {        return new UserService(getUserRepository());    }}class UserService {    private final UserRepository repository;    UserService(UserRepository repository) {        this.repository = repository;    }    String authenticate(String username, String password) {        return repository.authenticate(username, password);    }}interface LocalUserRepositoryComponent extends UserRepositoryComponent {    default UserRepository getUserRepository() {        return new UserRepository() { public String authenticate(String username, String password) {     return "LocalAuthed"; }        };    }}interface MongoUserRepositoryComponent extends UserRepositoryComponent {    default UserRepository getUserRepository() {        return new UserRepository() { public String authenticate(String username, String password) {     return "MongoAuthed"; }        };    }}class LocalApp implements UserServiceComponent, LocalUserRepositoryComponent {}class MongoApp implements UserServiceComponent, MongoUserRepositoryComponent {}

以上代码自2013年1月9日起在Java 8上编译。


因此,可以的Java 8做cake- 喜欢 的图案? 是。

它像Scala一样简洁,还是像Java中的其他模式一样有效(即依赖注入)?可能不是,上面的草图需要大量文件,并且不如Scala简洁。

综上所述:

  • 可以通过扩展我们期望的基本接口来模拟自类型(蛋糕模式所需)。
  • 接口不能具有内部类(如@Owen所述),因此我们可以使用匿名类。
  • val``var
    可以通过使用静态哈希图(和延迟初始化)来模拟,也可以由类的客户端简单地将值存储在其侧面(如UserService一样)进行模拟。
  • 我们可以通过使用
    this.getClass()
    默认接口方法来发现我们的类型。
  • 正如@Owen指出的那样,使用接口无法实现路径依赖类型,因此,完整的蛋糕模式本质上是不可能的。但是,以上显示了可以将其用于依赖项注入。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508299.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号