1. 程式人生 > >查詢命令分離【其他模式】

查詢命令分離【其他模式】

over dso shm oid shared 命令 vat ava name

查詢命令分離

public class CQRS {
    /**
     * Command Query Responsibility Segregation【命令查詢職責分離】:
     *  查詢操作是冪等的,可以放心使用;但是使用命令操作時需要加倍小心。
     *  CQRS 一般和Event Sourcing【事件溯源】一起在 Domain Driven Design【領域驅動設計】中使用。
     */
    @Test
    public void all() {
        final UserCommand userCommand = new UserCommandImpl();
        userCommand.add(new User("zxd", 1));
        userCommand.add(new User("kristy", 2));

        final UserQuery userQuery = new UserQueryImpl();
        final User user = userQuery.getByName("zxd");
        assertNotNull(user);

        userCommand.update(new User("zxd", 3));
        userCommand.delete("zxd");
    }
}
@Data
class User{
    private final String name;
    private final int order;
}

interface UserCommand{
    void add(User user);
    void update(User user);
    void delete(String username);
}
interface UserQuery{
    User getByName(String name);
}
class UserCommandImpl implements UserCommand{
    @Override
    public void add(User user) {
        SharedSource.USERS.putIfAbsent(user.getName(), user);
    }

    @Override
    public void update(User user) {
        SharedSource.USERS.putIfAbsent(user.getName(), user);
    }

    @Override
    public void delete(String username) {
        SharedSource.USERS.remove(username);
    }
}
class UserQueryImpl implements UserQuery{

    @Override
    public User getByName(String name) {
        return SharedSource.USERS.get(name);
    }

}
interface SharedSource {
    ConcurrentMap<String, User> USERS = new ConcurrentHashMap<>();
}

查詢命令分離【其他模式】