1. 程式人生 > >標記介面模式【其他模式】

標記介面模式【其他模式】

標記介面模式

public class Marker {
    /**
     * 標記模式:
     * Using empty interfaces as markers to distinguish special treated objects。
     * 使用空的標記介面來區分需要特殊處理的物件。
     */
    @SuppressWarnings("boxing")
    @Test
    public void all() {
        final PermissionServiceImpl serviceImpl = new PermissionServiceImpl();
        final Map<Permission, Boolean> map = serviceImpl.getPermission("zxd");
        Assert.assertTrue(map.get(ReadPermission.ALL));
    }
}

interface Permission {
}

enum ReadPermission implements Permission {
    SELF, ALL;
}

enum WritePermission implements Permission {
    SELF;
}

interface PermissionService {
    /**
     * 高內聚,將所有的許可權操作都封裝在一處
     */
    Map<Permission, Boolean> getPermission(String userId);
}

class PermissionServiceImpl implements PermissionService {

    @Override
    public Map<Permission, Boolean> getPermission(String userId) {
        final Map<Permission, Boolean> map = Maps.newHashMap();
        if ("zxd".equals(userId)) {
            map.put(ReadPermission.ALL, Boolean.TRUE);
        }

        map.put(ReadPermission.SELF, Boolean.TRUE);
        map.put(WritePermission.SELF, Boolean.TRUE);
        return map;
    }
}