美文网首页
装饰者模式

装饰者模式

作者: keith666 | 来源:发表于2016-05-15 23:24 被阅读30次

    Intent

    • Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
    • Client-specified embellishment of a core object by recursively wrapping it.
    • Wrapping a gift, putting it in a box, and wrapping the box.

    Structure

    Decorator by keith
  1. 实现代码:
  2. public class Decorator {
        public static void main(String[] args) {
            Beverage beverage=new HouseBlend();
            System.out.println(beverage.getDescription()+"  $"+beverage.cost());
            beverage=new Mocha(beverage);
            System.out.println(beverage.getDescription()+"  $"+beverage.cost());
            beverage=new Soy(beverage);
            System.out.println(beverage.getDescription()+"  $"+beverage.cost());
        }
    }
    abstract class Beverage {
        String description = "Unknown Beverage";
    
        public String getDescription() {
            return description;
        }
    
        // calculate the cost of the beverage
        public abstract double cost();
    }
    class HouseBlend extends Beverage {
    
        public HouseBlend() {
            description = getClass().getSimpleName();
        }
    
        @Override
        public double cost() {
            return 1.99;
        }
    }
    class DarkRoast extends Beverage {
    
        public DarkRoast() {
            description = getClass().getSimpleName();
        }
    
        @Override
        public double cost() {
            return 0.89;
        }
    }
    //base decorator class
    abstract class CondimentDecorator extends Beverage {
        Beverage beverage;
    
        public CondimentDecorator(Beverage beverage) {
            this.beverage = beverage;
        }
    
        public abstract String getDescription();
    }
    class Mocha extends CondimentDecorator {
    
        public Mocha(Beverage beverage) {
            super(beverage);
        }
    
        @Override
        public String getDescription() {
            return beverage.getDescription() + "," + getClass().getSimpleName();
        }
    
        @Override
        public double cost() {
            return 0.2 + beverage.cost();
        }
    }
    class Soy extends CondimentDecorator {
    
        public Soy(Beverage beverage) {
            super(beverage);
        }
    
        @Override
        public String getDescription() {
            return beverage.getDescription() + "," + getClass().getSimpleName();
        }
    
        @Override
        public double cost() {
            return 0.1 + beverage.cost();
        }
    }
    

    Notice:

    • 装饰类和组件是同一种类型,并扩展了而外的功能
    • Java I/O中的BufferedInputStream,FilterInputStream等也用到了装饰者模式

    Reference:

    1. Design Patterns

    相关文章

      网友评论

          本文标题:装饰者模式

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