美文网首页设计模式
装饰者模式(DecoratorPattern)

装饰者模式(DecoratorPattern)

作者: jsjack_wang | 来源:发表于2018-01-26 15:04 被阅读0次

    1.定义

    装饰者模式将职责附加在一个对象上,如果功能扩展,装饰者模式提供比继承更具弹性的替代方案
    

    2.小栗子(咖啡店案例)

    2.1 Coffee.java 咖啡抽象类
    public abstract class Coffee {
        protected int price;
        protected String name;
    
        public int getPrice() {
            return this.price;
        }
    
        public String getName() {
            return this.name;
        }
    }
    
    2.2 SimpleCoffee.java 普通咖啡类
    public class SimpleCoffee extends Coffee {
        @Override
        public int getPrice() {
            return 24;
        }
    
        @Override
        public String getName() {
            return "SimpleCoffee";
        }
    }
    
    2.3 DecoratorCoffee.java 装饰咖啡类
    public class DecoratorCoffee extends Coffee {
        protected Coffee coffee;
    
        public DecoratorCoffee(Coffee coffee) {
            this.coffee = coffee;
        }
    
        @Override
        public int getPrice() {
            return this.coffee.getPrice();
        }
    
        @Override
        public String getName() {
            return this.coffee.getName();
        }
    }
    
    2.4 SugarCoffee.java 加糖咖啡类
    public class SugarCoffee extends DecoratorCoffee {
        public SugarCoffee(DecoratorCoffee decoratorCoffee) {
            super(decoratorCoffee);
        }
    
        @Override
        public int getPrice() {
            return super.getPrice() + 2;
        }
    
        @Override
        public String getName() {
            return "Sugar + " + super.getName();
        }
    }
    

    3 测试类

    public class DecoratorPatternDemo {
        public static void main(String[] args) {
            DecoratorCoffee decoratorCoffee = new SugarCoffee(new DecoratorCoffee(new SimpleCoffee()));
            System.out.println("NAME:" + decoratorCoffee.getName() + "  PRICE:" + decoratorCoffee.getPrice());
        }
    }
    

    4 总结

    看到测试中的代码是不是有点似曾相识,不错java.io.*中,常常会用到类似的代码,其实也是用装饰者模式。它的装饰父类是FilterInputStream/FilterOutputStream,有空去看看流这一块的源码吧。
    

    相关文章

      网友评论

        本文标题:装饰者模式(DecoratorPattern)

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