1. 程式人生 > >裝飾者模式和工廠模式

裝飾者模式和工廠模式

1.java io就是裝飾者模式,圖看這裡https://www.cnblogs.com/intsmaze/p/5202213.html

package main;

abstract class Component{   //元件
    abstract String methodA();
    abstract int methodB();
}
class ConcreteComponent extends Component{  //具體元件
    @Override
    String methodA() {
        return "具體方法A";
    }
    @Override
    int methodB() {
        return 10;
    }
}
abstract class Decorator extends Component{  //裝飾
}
class ConcreteDecorator extends Decorator{   //具體裝飾
    private Component component;
    ConcreteDecorator(Component component){
        this.component=component;
    }
    @Override
    String methodA() {
        return component.methodA()+",裝飾方法A";
    }

    @Override
    int methodB() {
        return component.methodB()+3;
    }
}
public class Test {
    public static void main(String[] args){
        Component component=new ConcreteComponent();
        component=new ConcreteDecorator(component);
        component=new ConcreteDecorator(component);
        component=new ConcreteDecorator(component);
        System.err.println(component.methodA());
        System.err.println(component.methodB());
    }
}

2.簡單工廠模式(靠if來判斷),工廠模式(靠子類來生成),抽象工廠模式(選擇一個工廠,生產的全部是這個工廠的產品),看下面的筆記http://www.runoob.com/design-pattern/abstract-factory-pattern.html