Java8的蛋糕模式可能吗?

Seb*_*ber 30 java scala java-8 cake-pattern

我只是想知道:使用Java 8,并且可以在接口中添加实现(有点像Scala特性),是否可以实现蛋糕模式,就像我们在Scala中可以做的那样?

如果是,有人可以提供代码片段吗?

Ale*_*rlo 27

从其他答案中获得灵感,我提出了以下(粗略)类层次结构,类似于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 {}
Run Code Online (Sandbox Code Playgroud)

以上编译于2013年1月9日在Java 8上编译.


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

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

综上所述:

  • 可以通过扩展我们期望的基本接口来模拟自我类型(根据蛋糕模式的需要).
  • 接口不能有内部类(如@Owen所述),所以我们可以使用匿名类.
  • val并且var可以通过使用静态hashmap(和延迟初始化)来模拟,或者通过类的客户端简单地将值存储在他们一边(就像UserService那样).
  • 我们可以通过this.getClass()在默认接口方法中使用来发现我们的类型.
  • 正如@Owen指出的那样,使用接口是不可能的路径依赖类型,因此完整的蛋糕模式本质上是不可能的.但是,上面显示可以将其用于依赖注入.