2014年6月21日 星期六

設計模式 - Decorator

介紹一下 Decorator (裝飾者模式)


  • 在不改變一個物件本身的功能的基礎上,動態地給一個物件增加額外的職責(是物件不是整個類別),替代繼承的方式之一。其行為模式如下圖所例:













  • 實際應用 Java I/O
            FileInputStream fis = new FileInputStream("/objects.gz");
            BufferedInputStream bis = new BufferedInputStream(fis);
               GzipInputStream gis = new GzipInputStream(bis);
                 ObjectInputStream ois = new ObjectInputStream(gis);

        • 類別圖

        • 範例程式

        //飲料 Beverage  抽像類別
        public abstract class Beverage {
            private String description;
         
            public abstract String getDescription();
         
            public abstract double cost();
        }
        //飲料 咖啡 繼承 Beverage
        public class Coffee extends Beverage {
        
            public Coffee () {
                // TODO Auto-generated constructor stub
            }
        
            @Override
            public String getDescription() {
                return "This is Coffee";
            }
        
            @Override
            public double cost() {
                return 20;
            }
        
        }
        // 調味品 為一個裝飾者的抽象類別
        public abstract class CondimentDecorator extends Beverage {
        
            protected Beverage beverage;
         
            public CondimentDecorator(Beverage beverage) {
                this.beverage = beverage;
            }
        }
        // 牛奶 繼承 CondimentDecorator 
        public class Milk extends CondimentDecorator {
        
            public Milk(Beverage beverage) {
                super(beverage);
            }
        
            @Override
            public String getDescription() {
                return super.beverage.getDescription() + ", add some Milk";
            }
        
            /* (non-Javadoc)
             * @see com.sample.Beverage#cost()
             */
            @Override
            public double cost() {
             return super.beverage.cost() + 5;
            }
        
        }
        // 摩卡 繼承 CondimentDecorator 
        public class Mocha extends CondimentDecorator {
        
            public Mocha(Beverage beverage) {
                super(beverage);
            }
        
            @Override
            public String getDescription() {
                return super.beverage.getDescription() + ", add some Mocha";
            }
        
            @Override
            public double cost() {
                return super.beverage.cost() + 15;
            }
        
        }
        
        public class Main {
            public static void main(String[] args) {
               Beverage beverage = new Coffee();
               beverage = new Milk(beverage);
               beverage = new Mocha(beverage);
               System.out.println("價格 : "+beverage.cost());
               System.out.println("描述 : "+beverage.getDescription());
            }
        }
        

        沒有留言:

        張貼留言