美文网首页
设计模式-装饰器(Decorator)模式

设计模式-装饰器(Decorator)模式

作者: qyfl | 来源:发表于2019-11-19 15:16 被阅读0次

    主要角色

    • 实体类
    • 装饰者

    职责

    动态的给类加模块

    类图

    类关系示意图

    代码

    public abstract class ABattercake {
        protected abstract String getDesc();
        protected abstract int cost();
    }
    ---
    public abstract class AbstractDecorator extends ABattercake {
        private ABattercake aBattercake;
    
        public AbstractDecorator(ABattercake aBattercake) {
            this.aBattercake = aBattercake;
        }
    
        protected abstract void doSomething();
    
        @Override
        protected String getDesc() {
            return this.aBattercake.getDesc();
        }
    
        @Override
        protected int cost() {
            return this.aBattercake.cost();
        }
    }
    ---
    public class Battercake extends ABattercake {
        @Override
        protected String getDesc() {
            return "煎饼";
        }
    
        @Override
        protected int cost() {
            return 8;
        }
    }
    ---
    public class EggDecorator extends AbstractDecorator {
        public EggDecorator(ABattercake aBattercake) {
            super(aBattercake);
        }
    
        @Override
        protected void doSomething() {
    
        }
    
        @Override
        protected String getDesc() {
            return super.getDesc()+" 加一个鸡蛋";
        }
    
        @Override
        protected int cost() {
            return super.cost()+1;
        }
    }
    ---
    public class SausageDecorator extends AbstractDecorator{
        public SausageDecorator(ABattercake aBattercake) {
            super(aBattercake);
        }
    
        @Override
        protected void doSomething() {
    
        }
    
        @Override
        protected String getDesc() {
            return super.getDesc()+" 加一根香肠";
        }
    
        @Override
        protected int cost() {
            return super.cost()+2;
        }
    }
    

    使用

    public class Test {
        public static void main(String[] args) {
            ABattercake aBattercake;
            aBattercake = new Battercake();
            aBattercake = new EggDecorator(aBattercake);
            aBattercake = new EggDecorator(aBattercake);
            aBattercake = new SausageDecorator(aBattercake);
    
            System.out.println(aBattercake.getDesc()+" 销售价格:"+aBattercake.cost());
        }
    }
    

    技巧

    • 装饰器的作用就像是给一张相片装不同的相框一样。

    相关文章

      网友评论

          本文标题:设计模式-装饰器(Decorator)模式

          本文链接:https://www.haomeiwen.com/subject/pydhictx.html