美文网首页
装饰模式

装饰模式

作者: 要学的东西太多了 | 来源:发表于2018-10-31 12:55 被阅读0次

装饰模式是一种用于替代继承的技术,它通过一种无须定义子类的方式来给对象动态增加职责,使用对象之间的关联关系取代类之间的继承关系。这种模式可以由客户端来决定要执行哪些行为,和执行行为的顺序。常用的java.IO对象输入输出流就是采用这种模式,示例如下:

public class Decorate {
    public static void main(String[] args){
        Decorate decorate = new Decorate();
        AssemblingComputer cpu=decorate.new AssemblingCpu();
        AssemblingComputer 主板=decorate.new Assembling主板();
        AssemblingComputer 硬盘=decorate.new Assembling硬盘();
        AssemblingComputer 内存条=decorate.new Assembling内存条();
        主板.setAssemblingComputer(cpu);
        cpu.setAssemblingComputer(硬盘);
        硬盘.setAssemblingComputer(内存条);
        主板.selfWork();
    }

    abstract class AssemblingComputer{
        private String step;
        private AssemblingComputer assemblingComputer;
        public void setAssemblingComputer(AssemblingComputer assemblingComputer) {
            this.assemblingComputer = assemblingComputer;
        }

        public AssemblingComputer(String step) {
            this.step = step;
        }

        public String getStep() {
            return step;
        }

        public Decorate.AssemblingComputer getAssemblingComputer() {
            return assemblingComputer;
        }

        public abstract void selfWork();
    }

    class Assembling主板 extends AssemblingComputer{

        public Assembling主板() {
            super("主板");
        }

        @Override
        public void selfWork(){
            System.out.println("组装"+getStep());
            if(getAssemblingComputer()!=null){
                getAssemblingComputer().selfWork();
            }
        }
    }

    class AssemblingCpu extends AssemblingComputer{

        public AssemblingCpu() {
            super("CPu");
        }

        @Override
        public void selfWork(){
            System.out.println("组装"+getStep());
            if(getAssemblingComputer()!=null){
                getAssemblingComputer().selfWork();
            }
        }
    }

    class Assembling硬盘 extends AssemblingComputer{

        public Assembling硬盘() {
            super("硬盘");
        }

        @Override
        public void selfWork(){
            System.out.println("组装"+getStep());
            if(getAssemblingComputer()!=null){
                getAssemblingComputer().selfWork();
            }
        }
    }

    class Assembling内存条 extends AssemblingComputer{

        public Assembling内存条() {
            super("内存条");
        }

        @Override
        public void selfWork(){
            System.out.println("组装"+getStep());
            if(getAssemblingComputer()!=null){
                getAssemblingComputer().selfWork();
            }
        }
    }
}

相关文章

网友评论

      本文标题:装饰模式

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