W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
裝飾模式在不鏈接其結(jié)構(gòu)的情況下向現(xiàn)有對象添加新功能。
它是一種結(jié)構(gòu)型模式,因為它充當現(xiàn)有類的包裝器。
裝飾模式創(chuàng)建一個裝飾器類來包裝原始類并提供其他功能。
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é)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: