原型继承模式【其他模式】

原型模式

public class Property {
    /**
     *  Property Pattern【原型继承模式】
     */
    @Test
    public void all() {
        final Map<String, Object> properties = Maps.newHashMap();
        properties.put("name", "zxd");
        properties.put("age", 28);
        final ProtptypeImpl parent = ProtptypeImpl.of(Prototype.NUll, properties);

        final Map<String, Object> childProps = Maps.newHashMap();
        properties.put("name", "kristy");
        final ProtptypeImpl child = ProtptypeImpl.of(parent, childProps);

        assertEquals("kristy", String.valueOf(child.get("name")));
        assertEquals(Integer.valueOf(28), Integer.valueOf(String.valueOf(child.get("age"))));
    }
}

interface Prototype {
    void put(String key, Object value);

    boolean has(String key);

    Object get(String key);

    void remove(String key);

    Prototype NUll = new Prototype() {
        @Override 
        public void put(String key, Object value) {
        }

        @Override 
        public boolean has(String key) {
            return false;
        }

        @Override 
        public Object get(String key) {
            return null;
        }

        @Override 
        public void remove(String key) {
        }
    };
}

@Value(staticConstructor = "of")
class ProtptypeImpl implements Prototype {

    private final Prototype prototype;
    private final Map<String, Object> properties;

    @Override
    public void put(String key, Object value) {
        properties.put(key, value);
    }

    @Override
    public Object get(String key) {
        if (properties.containsKey(key)) {
            return properties.get(key);
        }
        return prototype.get(key);
    }

    @Override
    public void remove(String key) {
        properties.put(key, null);
    }

    @Override
    public boolean has(String key) {
        return get(key) != null;
    }
}

posted on 2019-01-05 14:31  竺旭东  阅读(76)  评论(0编辑  收藏  举报

导航