Java 裝飾模式

2018-01-17 18:31 更新

 Java設(shè)計(jì)模式 - 裝飾模式


裝飾模式在不鏈接其結(jié)構(gòu)的情況下向現(xiàn)有對(duì)象添加新功能。

它是一種結(jié)構(gòu)型模式,因?yàn)樗洚?dāng)現(xiàn)有類(lèi)的包裝器。

裝飾模式創(chuàng)建一個(gè)裝飾器類(lèi)來(lái)包裝原始類(lèi)并提供其他功能。

例子

interface Printer {
   void print();
}
class PaperPrinter implements Printer {
   @Override
   public void print() {
      System.out.println("Paper Printer");
   }
}
class PlasticPrinter implements Printer {
   @Override
   public void print() {
      System.out.println("Plastic Printer");
   }
}
abstract class PrinterDecorator implements Printer {
   protected Printer decoratedPrinter;
   public PrinterDecorator(Printer d){
      this.decoratedPrinter = d;
   }
   public void print(){
      decoratedPrinter.print();
   }  
}
class Printer3D extends PrinterDecorator {
   public Printer3D(Printer decoratedShape) {
      super(decoratedShape);    
   }
   @Override
   public void print() {
     System.out.println("3D.");
     decoratedPrinter.print();         
   }
}
public class Main {
   public static void main(String[] args) {
      Printer plasticPrinter = new PlasticPrinter();
      Printer plastic3DPrinter = new Printer3D(new PlasticPrinter());
      Printer paper3DPrinter = new Printer3D(new PaperPrinter());
      plasticPrinter.print();
      plastic3DPrinter.print();
      paper3DPrinter.print();
   }
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)