/** * 类的包装器 * 不改变接口,增加功能 * @author ruis * */ //创建一个打印机接口 public interface Printer {
void print(); } |
//纸张打印机 public class PaperPrinter implements Printer {
@Override public void print() { // TODO Auto-generated method stub System.out.println("Paper Printer"); }
}
|
//塑料打印机 public class PlasticPrinter implements Printer {
@Override public void print() { // TODO Auto-generated method stub System.out.println("Plastic Printer"); }
}
|
//装饰者打印机 public abstract class PrinterDecorator implements Printer {
//本包中可以使用 protected Printer decoratedPrinter; //形参为装饰者打印机 public PrinterDecorator(Printer d){ this.decoratedPrinter=d; } public void print(){ decoratedPrinter.print(); }
}
|
//3D打印机继承装饰者打印机功能 public class Printer3D extends PrinterDecorator {
//给3D打印机增加的一个功能 是装饰者打印机 public Printer3D(Printer decoratedShape) { super(decoratedShape); // TODO Auto-generated constructor stub } //3D打印机 装饰者打印机 @Override public void print(){ System.out.println("3D."); decoratedPrinter.print(); }
}
|
/** * 创建一个3D打印机,给3D打印机增加一个打印机功能 * @author ruis * */ public class Main {
public static void main(String[] args) { PlasticPrinter plasticPrinter = new PlasticPrinter(); Printer3D plastic3DPrinter = new Printer3D(new PlasticPrinter()); Printer3D paper3DPrinter = new Printer3D(new PaperPrinter()); plasticPrinter.print(); plastic3DPrinter.print(); paper3DPrinter.print(); } /** * Plastic Printer 3D. Plastic Printer 3D. Paper Printer */ }
|