1. 程式人生 > >《大話設計模式》簡讀

《大話設計模式》簡讀

感謝《大話設計模式》作者程傑

簡單工廠模式

客戶端不關心物件如何建立, 只需知道傳入工廠類的引數

計算器–面向物件–可維護、可複用、可擴充套件–業務與介面分離–業務分離(繼承)

/**
 * Operation 父類
 * 抽象類  用於代表實現類
 * @author xmd
 *
 */
abstract class Operation{
    public double NumberA;
    public double NumberB;
    public abstract double GetResult();
}
class OperationAdd extends Operation{
    @Override
public double GetResult() { return NumberA + NumberB; } } class OperationSub extends Operation{ @Override public double GetResult() { return NumberA - NumberB; } } class OperationMul extends Operation{ @Override public double GetResult() { return
NumberA * NumberB; } } class OperationDiv extends Operation{ @Override public double GetResult() { if(NumberB == 0){ throw new RuntimeException("除數為0"); } return NumberA / NumberB; } } /** * 簡單工廠 * 根據運算子號生成相應的實現類 * @author xmd * */ class OperationFactory { public
static Operation createOperation(String operate){ Operation opre = null; switch (operate) { case "+": opre = new OperationAdd(); break; case "-": opre = new OperationSub(); break; case "*": opre = new OperationMul(); break; case "/": opre = new OperationDiv(); break; } return opre; } } /** * 計算介面 * @author xmd * */ public class Jiandangongchang { public static void main(String[] args) { Operation oper; oper = OperationFactory.createOperation("+"); oper.NumberA=15; oper.NumberB=2; System.out.println(oper.GetResult()); } }

策略模式

封裝演算法,封裝規則,應用 於不同時間不同業務規則

讓演算法的變化,不會影響到使用演算法的客戶

商場收銀

/**
 * 抽象演算法類
 * @author xmd
 *
 */
abstract class Strategy{
    //演算法方法
    public abstract void AlgorithmInterface();
}

class ConcreteStrategyA extends Strategy{
    @Override
    public void AlgorithmInterface() {
        System.out.println("演算法A實現");
    }
}
class ConcreteStrategyB extends Strategy{
    @Override
    public void AlgorithmInterface() {
        System.out.println("演算法B實現");
    }
}
class ConcreteStrategyC extends Strategy{
    @Override
    public void AlgorithmInterface() {
        System.out.println("演算法C實現");
    }
}
/**
 * 上下文  維護對Strategy物件的引用  配置ConcreteStrategy
 * @author xmd
 *
 */
class Context{
    Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void ContextInterface(){
        strategy.AlgorithmInterface();
    }
}
/**
 * 策略模式:
 * 通過Context組合Strategy成員物件,
 * 傳入Context適當的Strategy成員物件,
 * 呼叫對應Strategy物件的algorithmInterface()。
 * @author xmd
 *
 */
public class celue {
    public static void main(String[] args) {
        Context context;
        //根據要求選擇策略  可用簡單工廠模式 實現選擇方案
        context = new Context(new ConcreteStrategyA());
        context.ContextInterface();

        context = new Context(new ConcreteStrategyB());
        context.ContextInterface();

        context = new Context(new ConcreteStrategyC());
        context.ContextInterface();
    }
}

裝飾模式

當某個物件的職責經常發生變化或者需要動態的增加職責

穿著

/**
 * 定義一個物件介面,可以給這些物件動態的新增職責
 * @author xmd
 *
 */
abstract class Component{
    public abstract void Opration();
}
/**
 * 定義一個具體的物件,也可以給這個物件新增職責
 * @author xmd
 *
 */
class ConcreteComponent extends Component{
    @Override
    public void Opration() {
        System.out.println("被裝飾的具體物件");
    }
}
/**
 * 裝飾抽象類, 從外類擴充套件Component的功能,但對於Component來說,是無需知道Decorate的存在
 * @author xmd
 *
 */
class Decorator extends Component{
    protected Component component;

    /**
     *實際執行Component的Opration()
     */
    @Override
    public void Opration() {
        if(component != null){
            component.Opration();
        }
    }

    public void setComponent(Component component) {
        this.component = component;
    }
}
/**
 * 具體的裝飾物件,起到給Component新增職責
 * @author xmd
 *
 */
class ConcreteDecoratorA extends Decorator{
    private String addedState;

    @Override
    public void Opration() {
        super.Opration();
        addedState = "new State";
        System.out.println("具體裝飾物件A的操作");
    }
}
/**
 * 具體的裝飾物件,起到給Component新增職責
 * @author xmd
 *
 */
class ConcreteDecoratorB extends Decorator{

    @Override
    public void Opration() {
        super.Opration();
        AddedBehacior();
        System.out.println("具體裝飾物件A的操作");
    }

    private void AddedBehacior() {
        System.out.println("具體裝飾物件B獨有方法");
    }
}

public class zhuangshi {
    public static void main(String[] args) {
        ConcreteComponent component = new ConcreteComponent();
        ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA();
        ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB();

        concreteDecoratorA.setComponent(component);//為component裝飾A
        concreteDecoratorB.setComponent(concreteDecoratorA);//為component裝飾A後再裝飾B
        concreteDecoratorB.Opration();
    }
}

代理模式

為其他物件提供一種代理以控制對這個物件的訪問。隱藏真實訪問物件,同時可以處理別的事情

/**
 * 定義了RealSubject和Proxy共用的介面
 * @author xmd
 *
 */
abstract class Subject{
    public abstract void Request();
}
/**
 * 真實類
 * @author xmd
 *
 */
class RealSubject extends Subject{

    @Override
    public void Request() {
        System.out.println("真實的請求");
    }
}
class Proxy extends Subject{
    private RealSubject realSubject;
    @Override
    public void Request() {
        if(realSubject == null)
            realSubject = new RealSubject();
        realSubject.Request();
    }
}
public class daili {
    public static void main(String[] args) {
        Proxy proxy = new Proxy();
        proxy.Request();
    }
}

工廠方法

克服了簡單工廠模式違背開閉原則,又保持了封裝物件建立過程的優點。一個類想要由自己的子類來定義某物件的建立過程。

雷鋒

/**
 * 雷鋒
 * @author xmd
 *
 */
class LeiFeng{
    public void Sweep(){
        System.out.println("掃地");
    }

    public void Wash(){
        System.out.println("洗衣");
    }
}
/**
 * 學習雷鋒學生
 * @author xmd
 *
 */
class Undergraduate extends LeiFeng{}
/**
 * 學習雷鋒志願者
 * @author xmd
 *
 */
class Volunteer extends LeiFeng{}

/**
 * 工廠介面 
 * @author xmd
 *
 */
interface Factory {
      public LeiFeng createLeiFeng();
}
/**
 * 工廠實現類 具體實現學生
 * @author xmd
 *
 */
class GraduateFactory  implements Factory{

    @Override
    public LeiFeng createLeiFeng() {
        return new Undergraduate();
    }
}
/**
 * 工廠實現類 具體實現學生
 * @author xmd
 *
 */
class VolunteerFactory  implements Factory{

    @Override
    public LeiFeng createLeiFeng() {
        return new Volunteer();
    }
}
public class gongchangfangfa {
    public static void main(String[] args) {
        Factory factory = new GraduateFactory();
        Undergraduate student = (Undergraduate) factory.createLeiFeng();
        student.Sweep();

        Factory VFactory = new VolunteerFactory();
        Volunteer volunteer = (Volunteer) VFactory.createLeiFeng();
        volunteer.Sweep();
    }
}

原型模式

用原型例項指定建立物件的種類,並且通過拷貝這些原型建立新的物件。簡化物件的建立過程,隱藏了物件建立的細節,又對效能大大的提高。頻繁使用一個物件,比如在迴圈體中

/**
 * 原型類 
 * 一個類重寫了 Object 內定義的 clone() ,需要同時實現 Cloneable 介面
 * 如果沒有implements Cloneable的類呼叫Object.clone()方法就會丟擲CloneNotSupportedException。 
 * (1)淺克隆(shallow clone),淺拷貝是指拷貝物件時僅僅拷貝物件本身和物件中的基本變數,而不拷貝物件包含的引用指向的物件。 
 *(2)深克隆(deep clone),深拷貝不僅拷貝物件本身,而且拷貝物件包含的引用指向的所有物件。 
 * @author xmd
 *
 */
abstract class Prototype implements Cloneable{
    private String id;

    public Prototype(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
    public abstract Prototype Clone() throws CloneNotSupportedException;
}
/**
 * 具體原型類
 * @author xmd
 *
 */
class ConcretePrototype extends Prototype{

    public ConcretePrototype(String id) {
        super(id);
    }

    @Override
    public Prototype Clone() throws CloneNotSupportedException {
            return (Prototype) this.clone();
    }
}
public class yuanxing {

    public static void main(String[] args) throws CloneNotSupportedException {
        ConcretePrototype cPrototype1 = new ConcretePrototype("1");
        ConcretePrototype cPrototype2 = (ConcretePrototype) cPrototype1.Clone();
        System.out.println(cPrototype1.getId());
        System.out.println(cPrototype2.getId());
    }
}

模板方法

定義一個操作中的演算法的骨架,而將一些步驟延遲到子類中,模板方法使得子類不改變演算法的結構,即可重定義該演算法的某些特定步驟。把不變行為搬移到超類,去除子類中的重複程式碼,體現它的優勢。通過父類呼叫子類,這是一種反向的控制

學生抄寫考試題

/**
 * 父類  包含了公共方法
 * @author xmd
 *
 */
abstract class AbstractClass{
    public abstract void PrimitveOperation1();
    public abstract void PrimitveOperation2();

    public void TemplateMethod(){
        PrimitveOperation1();
        PrimitveOperation2();
    }
}
class ConcreteClassA extends AbstractClass{

    @Override
    public void PrimitveOperation1() {
        System.out.println("A類方法1實現");
    }

    @Override
    public void PrimitveOperation2() {
        System.out.println("A類方法2實現");

    }
}
class ConcreteClassB extends AbstractClass{

    @Override
    public void PrimitveOperation1() {
        System.out.println("B類方法1實現");
    }

    @Override
    public void PrimitveOperation2() {
        System.out.println("B類方法2實現");

    }
}
public class mubanfangfa {
    public static void main(String[] args) {
        AbstractClass abstractClass;

        abstractClass = new ConcreteClassA();
        abstractClass.TemplateMethod();

        abstractClass = new ConcreteClassB();
        abstractClass.TemplateMethod();
    }
}

外觀模式

為子系統中的一組介面提供一個一致的介面,此模式定義了一個高層介面,這一介面使得這一子系統更加容易使用。1.減少客戶端處理的物件數目2.對客戶端遮蔽了子系統, 實現瞭解耦合

package dhsjms;

class SubSystemOne{
    public void MethodOne(){
        System.out.println("子系統方法一");
    }
}
class SubSystemTwo{
    public void MethodTwo(){
        System.out.println("子系統方法二");
    }
}
class SubSystemThree{
    public void MethodThree(){
        System.out.println("子系統方法三");
    }
}
class Facade{
    SubSystemOne subSystemOne;
    SubSystemTwo subSystemTwo;
    SubSystemThree subSystemThree;
    public Facade() {
        subSystemOne = new SubSystemOne();
        subSystemTwo = new SubSystemTwo();
        subSystemThree = new SubSystemThree();
    }

    public void MethodA(){
        System.out.println("方法組A---");
        subSystemOne.MethodOne();
        subSystemTwo.MethodTwo();
        subSystemThree.MethodThree();
    }
    public void MethodB(){
        System.out.println("方法組B---");
        subSystemOne.MethodOne();
        subSystemThree.MethodThree();
    }

}
public class waiguan {
    public static void main(String[] args) {
        Facade facade = new Facade();
        facade.MethodA();
        facade.MethodB();
    }

}

建造者模式

將一個複雜物件的構建和它的表示分離,使得同樣的構建過程可以建立不同的表示。建造者隱藏了該物件是如何組裝的,所以需要改變一個產品的的內部表示,只需要在定義一個新的具體的建造者就可以了

/**
 * 產品類,由多個部件組成
 */
class Product{
    List<String> parts = new ArrayList<String>();

    public void Add(String part){
        parts.add(part);
    }
    public void Show(){
        System.out.println("產品 建立 ----");
        for (String psrt:parts) {
            System.out.println(psrt);

        }
    }
}

/**
 * 抽象建造這類,確定產品倆個部件A,B組成,並宣告一個得到產品
 * 建造後結果的方法GetResult()
 */
abstract class Builder{
    public abstract void BuidPartA();
    public abstract void BuidPartB();
    public abstract Product GetResult();
}
class ConcreteBuilder1 extends Builder{
    private Product product = new Product();
    @Override
    public void BuidPartA() {
        product.Add("部件A");
    }

    @Override
    public void BuidPartB() {
        product.Add("部件B");
    }

    @Override
    public Product GetResult() {
        return product;
    }
}
class ConcreteBuilder2 extends Builder{
    private Product product = new Product();
    @Override
    public void BuidPartA() {
        product.Add("部件X");
    }

    @Override
    public void BuidPartB() {
        product.Add("部件Y");
    }

    @Override
    public Product GetResult() {
        return product;
    }
}
class Director{
    public void Construct(Builder builder){
        builder.BuidPartA();
        builder.BuidPartB();
    }
}
public class jianzaozhe {
    public static void main(String[] args){
        Director director = new Director();
        Builder builder1 = new ConcreteBuilder1();
        Builder builder2 = new ConcreteBuilder2();

        director.Construct(builder1);
        Product product1 = builder1.GetResult();
        product1.Show();

        director.Construct(builder2);
        Product product2 = builder2.GetResult();
        product2.Show();
    }
}

觀察者

釋出-訂閱模式,定義了一種一對多的依賴關係,讓多個觀察者物件,同時監聽一個主題物件,這個主題物件在狀態發生變化時,會通知所有的觀察者物件,是它們能夠自動更新自己。解除了通知者和具體觀察者的耦合,讓耦合的雙方依賴於抽象,使得各自的變換不會影響到另一方。當一個物件的改變,需要同時改變其他物件的時候,而且它不知道具體有多少物件需要改變

/**
 * 抽象通知者,把所有觀察者物件的引用儲存在一個聚類裡,每個主題都可以有任何熟量的觀察者。
 */
abstract class Subject{
     private List<Observer> observers = new ArrayList<Observer>();
     //增加觀察者
     public void Attach(Observer observer){
         observers.add(observer);
     }

     //移除觀察者
     public void Detach(Observer observer){
         observers.remove(observer);
     }
     //通知
    public void Notify(){
        for (Observer o:observers) {
            o.update();
        }
    }
}

/**
 * 抽象觀察者,為所有的具體觀察者定義一個介面,在得到主題的通知是更新自己。
 */
abstract class Observer{
    public abstract void update();
}

/**
 * 具體通知者,將有關狀態存入具體觀察者物件
 */
class ConcreteSubject extends Subject{
    //具體被觀察者的狀態
    private String subjectState;

    public void setSubjectState(String subjectState) {
        this.subjectState = subjectState;
    }

    public String getSubjectState() {
        return subjectState;
    }
}
class ConcreteObserver extends Observer{
    private String name;
    private String observerState;
    private ConcreteSubject subject;

    public ConcreteObserver(String name, ConcreteSubject subject) {
        this.name = name;
        this.subject = subject;
    }

    @Override
    public void update() {
        observerState = subject.getSubjectState();
        System.out.println("觀察者的最新狀態是:"+name+observerState);
    }

    public ConcreteSubject getSubject() {
        return subject;
    }

    public void setSubject(ConcreteSubject subject) {
        this.subject = subject;
    }
}
public class guanchazhe {
    public static void main(String[] args){
        ConcreteSubject s = new ConcreteSubject();
        s.Attach(new ConcreteObserver("X",s));
        s.Attach(new ConcreteObserver("Y",s));
        s.Attach(new ConcreteObserver("Z",s));

        s.setSubjectState("ABC");
        s.Notify();
    }
}

抽象工廠

提供一個建立一系列相關或相關依賴物件的介面,而無需指定他們具體的類。在類內部對產品族的關聯關係進行定義和描述,而不必專門引入一個新的類來進行管理

/***
 * 用於客服端訪問,解除與具體資料庫訪問的耦合
 */
class Department{}
interface IDepartment{
    void Insert(Department department);
    Department getDepartment(int id);
}

class SqlserverDepartment implements IDepartment{
    @Override
    public void Insert(Department department) {
        System.out.println("Sqlserver  insert Department");
    }

    @Override
    public Department getDepartment(int id) {
        System.out.println("Sqlserver  select  Department");
        return null;
    }
}
class AccessDepartment implements  IDepartment{
    @Override
    public void Insert(Department department) {
        System.out.println("Access  insert Department");
    }

    @Override
    public Department getDepartment(int id) {
        System.out.println("Access  select Department");
        return null;
    }
}

/**
 * IFactory介面,定義了一個用來建立Department物件 的 抽象工廠介面
 */
interface IFactory{
    IDepartment CreateDepartment();
}
class SqlserverFactory implements  IFactory{
    @Override
    public IDepartment CreateDepartment() {
        return new SqlserverDepartment();
    }
}
class AccessFactory implements  IFactory{
    @Override
    public IDepartment CreateDepartment() {
        return new AccessDepartment();
    }
}

public class chouxianggongchang {
    public static void main(String[] args){
        Department department = new Department();

        IFactory iFactory = new AccessFactory();//只需更換工廠即可

        IDepartment idepartment = iFactory.CreateDepartment();
        idepartment.Insert(department);
        idepartment.getDepartment(2);

    }
}

狀態模式

當一個物件的內在狀態改變時,允許改變其行為,這個物件看起來改變了其類。消除龐大的條件分支,將特定狀態的行為放入一個物件中。通過把各種狀態判斷邏輯分佈到State的子類中,減少相互之間的依賴

/**
 * 抽象狀態
 */
abstract class State{
    public abstract void Hanlde(Context context);
}

/**
 * 具體狀態1
 */
class ConcreteStateA extends State{
    @Override
    public void Hanlde(Context context) {
        context.setState(new ConcreteStateB());//轉入新的狀態
    }
}
class ConcreteStateB extends State{
    @Override
    public void Hanlde(Context context) {
        context.setState(new ConcreteStateA());
    }
}
class Context{
    private State state;

    public Context(State state) {
        this.state = state;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }
    public void Request(){
        state.Hanlde(this);
    }
}
public class zhuangtai {
    public static void main(String[] args){
        Context context = new Context(new ConcreteStateA());
        context.Request();
        context.Request();
        context.Request();
        context.Request();
        context.Request();
    }
}

介面卡

將一個類的介面轉換成客戶希望的另一個介面, 使得原本由於介面不相容不能再一起工作的類,可以在一起工作。通過引入介面卡,可以複用現有的類,而不需要修改原始碼,將目標類和適配者解耦合,解決了介面和複用環境不一致的情況。

/**
 * 客戶所期待的介面
 */
class Target{
    public void Request(){
        System.out.println("普通介面");
    }
}

/**
 * 需要適配的類
 */
class Adaptee{
   public void SpecificRequest(){
       System.out.println("特殊請求");
   }
}

/**
 * 將源介面轉成目標介面
 */
class Adapter extends Target{
    private Adaptee adaptee = new Adaptee();

    @Override
    public void Request() {
        adaptee.SpecificRequest();
    }
}

public class shipeiqi {
    public static void main(String[] args){
        Target target = new Adapter();
        target.Request();
    }
}

備忘錄

在不破壞封裝性的前提下,捕獲一個物件的內部狀態,並在該物件之外儲存這個狀態,這樣以後可將物件恢復到儲存的狀態。把要儲存的細節放到備忘錄中,當修改儲存的資訊時,不會影響客戶端

/**
 * 發起類
 */
class Originator{
    private String state;
    //建立一個備忘錄,將當前需要儲存的資訊匯入並new出一個Memento物件
    public Memento CreateMenento(){
        return new Memento(state);
    }
    //恢復資料
    public void SetMemento(Memento memento){
        state = memento.getState();
    }
    public void Show(){
        System.out.println("state" + state);
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
}

/**
 * 備忘錄
 */
class Memento{
    private String state;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }
}

/**
 * 管理者
 */
class Caretaker{
    private Memento memento;

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}

public class beiwanglu {
    public static void main(String[] args){
        Originator originator = new Originator();
        originator.setState("On");
        originator.Show();

        Caretaker caretaker = new Caretaker();
        caretaker.setMemento(originator.CreateMenento());

        originator.setState("Off");
        originator.Show();

        originator.SetMemento(caretaker.getMemento());//恢復
        originator.Show();
    }
}

組合

將物件組合成樹形結構,以表示整體-部分的結構, 使得使用者對單個物件和組合物件的使用具有一致性。簡化客戶端程式碼,在定義組合的那些類中不需要寫一些充斥著選擇語句的函式。基本物件可以被組合成更復雜的組合物件,而這個組合物件又可以被組合,這樣不斷的遞迴下去

/**
 * 用於訪問和管理Component的子部件
 */
abstract class Component{
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void Add(Component component);
    public abstract void Remove(Component component);
    public abstract void Display(int depth);
}

/**
 * 葉子節點
 */
class Leaf extends Component{
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void Add(Component component) {
        System.out.println("not leaf add");
    }

    @Override
    public void Remove(Component component) {
        System.out.println("npt leaf Remove");
    }

    @Override
    public void Display(int depth) {
        while(depth>0){
            System.out.print("-");
            depth--;
        }
        System.out.println(name);
    }
}

/**
 * 枝點
 */
class Composite extends Component{
    private List<Component> childrens = new ArrayList<Component>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void Add(Component component) {
        childrens.add(component);
    }

    @Override
    public void Remove(Component component) {
        childrens.remove(component);
    }

    @Override
    public void Display(int depth) {
        int d = depth;
        while(d>0){
            System.out.print("-");
            d--;
        }
        System.out.println(name);

        for (Component component : childrens ) {
            component.Display(depth+2);
        }
    }
}
public class zuhe {
    public static void main(String[] args){
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite comp = new Composite("Composite X");
        comp.Add(new Leaf("Leaf Xa"));
        comp.Add(new Leaf("Leaf Xb"));

        root.Add(comp);

        Composite comp2 = new Composite("Composite XY");
        comp2.Add(new Leaf("Leaf XYa"));
        comp2.Add(new Leaf("Leaf XYb"));
        root.Add(comp2);

        Leaf leaf = new Leaf("Leaf D");
        root.Add(leaf);
        root.Remove(leaf);

        root.Display(1);
    }

}

迭代器

提供一種方法順序訪問一個聚合物件中各個元素,而又不暴露該物件的內部表示.分離了集合物件的遍歷行為,不暴露集合的內部結構,又可讓外部訪問集合內的資料

/**
 * Iterator抽象類
 */
abstract class Iterator{
    public abstract Object First();
    public abstract Object Next();
    public abstract boolean IsDone();
    public abstract Object CurrentItem();
}
abstract class Aggregate{
    public abstract Iterator CreateIterator();//建立迭代器
}
class ConcreteIterator extends Iterator{
    private ConcreteAggregate concreteAggregate;
    private  int current=0;

    public ConcreteIterator(ConcreteAggregate concreteAggregate) {
        this.concreteAggregate = concreteAggregate;
    }

    @Override
    public Object First() {
        return concreteAggregate.getObject(0);
    }

    @Override
    public Object Next() {
        Object ret = null;
        current++;
        if(current < concreteAggregate.getCount()){
            ret = concreteAggregate.getObject(current);
        }
        return ret;
    }

    @Override
    public boolean IsDone() {
        return current >= concreteAggregate.getCount();
    }

    @Override
    public Object CurrentItem() {
        return concreteAggregate.getObject(current);
    }
}
class ConcreteAggregate extends Aggregate{
    private List<Object> items = new ArrayList<Object>();

    @Override
    public Iterator CreateIterator() {
        return new ConcreteIterator(this);
    }
    public int getCount(){
        return items.size();
    }

    public Object getObject(int index){
        return items.get(index);
    }

    public void setObject(Object object){
        items.add(object);
    }
}
public class diedaiqi {
        public static void main(String[] args){
            ConcreteAggregate aggregate = new ConcreteAggregate();
            aggregate.setObject("一");
            aggregate.setObject("二");
            aggregate.setObject("四");
            aggregate.setObject("三");
            aggregate.setObject("七");
            aggregate.setObject("九");
            aggregate.setObject("八");

            Iterator iterator = new ConcreteIterator(aggregate);

            Object object = iterator.First();
            while(!iterator.IsDone()){
                System.out.println(iterator.CurrentItem());
                iterator.Next();
            }
        }
}

單例

保證一個類只有一個例項,並提供一個訪問它的全域性訪問點

class Singleton{
    private static Singleton singleton;
    private Singleton(){}

    public static Singleton getSingleton(){
        if(singleton == null) singleton = new Singleton();
        return singleton;
    }
}
public class danli {
    public static void main(String[] args){
        Singleton s1 = Singleton.getSingleton();
        Singleton s2 = Singleton.getSingleton();
        if(s1 == s2){
            System.out.println("==");
        }
    }
}

橋接模式

將抽象部分與它的實現部分分離,使它們都可以獨立的變化。1.類和類繼承關係會保持較小的規模,不太可能增長為龐然大物。2.使得抽象之間可以獨立的變化,起到了解耦合的作用。使用場景: 一個構件有多於一個的抽象化角色和實現化角色,系統需要它們之間進行動態耦合。

abstract class Implementor{
    public abstract void