設計模式學習總結

前言

學習總結吧,參考了 GOF 設計模式以及網上許多例子,實際上也就是個代碼+流程圖重新排碼,方便後續查閱理解

設計模式

創建型

抽象工廠模式

在這裏插入圖片描述

////////////////////////////////////////////////////////////////////////////
// 產品接口 1
interface IProduct1 {  
    public void show();  
}  
// 產品接口 2
interface IProduct2 {  
    public void show();  
}  

// 產品實現 1  
class Product1 implements IProduct1 {  
    public void show() {  
        System.out.println("這是1型產品");  
    }  
}  
// 產品實現 2
class Product2 implements IProduct2 {  
    public void show() {  
        System.out.println("這是2型產品");  
    }  
}  

////////////////////////////////////////////////////////////////////////////
// 工廠接口   
interface IFactory {  
    public IProduct1 createProduct1();  
    public IProduct2 createProduct2();  
}  
// 工廠實現
class Factory implements IFactory{  
    public IProduct1 createProduct1() {  
        return new Product1();  
    }  
    public IProduct2 createProduct2() {  
        return new Product2();  
    }  
}  
////////////////////////////////////////////////////////////////////////////
// 調用 
public class Client {  
    public static void main(String[] args){  
        IFactory factory = new Factory();  
        factory.createProduct1().show();  
        factory.createProduct2().show();  
    }  
}  

單例模式

在這裏插入圖片描述
餓漢式

public class Singleton {  
    private static Singleton singleton = new Singleton();  
    private Singleton(){}  
    
    public static Singleton getInstance(){  
        return singleton;  
    }  
} 

懶漢式

public class Singleton {  
    private static Singleton singleton;  
    private Singleton(){}  
      
    public static synchronized Singleton getInstance(){  
        if(singleton==null){  
            singleton = new Singleton();  
        }  
        return singleton;  
    }  
} 

工廠方法模式

在這裏插入圖片描述

簡單工廠:

/////////////////////////////////////////////////////////////////////////////
// 抽象產品角色
interface Fruit{	// 定義一個水果接口
	public void eat() ;	// 吃水果
}

// 具體產品角色 1
class Apple implements Fruit{
	public void eat(){
		System.out.println("** 吃蘋果。") ;
	}
};
// 具體產品角色 2
class Orange implements Fruit{
	public void eat(){
		System.out.println("** 吃橘子。") ;
	}
};

/////////////////////////////////////////////////////////////////////////////
// 工廠角色
class Factory{	// 定義工廠類
	public static Fruit getInstance(String className){
		Fruit f = null ;
		if("apple".equals(className)){	// 判斷是否要的是蘋果的子類
			f = new Apple() ;
		}
		if("orange".equals(className)){	// 判斷是否要的是橘子的子類
			f = new Orange() ;
		}
		return f ;
	}
};

///////////////////////////////////////////////////////////////////////////
// 測試
public class InterfaceCaseDemo05{
	public static void main(String args[]){

		// 通過傳入的名稱來創建實例
		Fruit f = Factory.getInstance(args[0]) ;	// 實例化接口
		
		if(f!=null){	// 判斷是否取得實例
			f.eat() ;
		}
	}
};

工廠方法

////////////////////////////////////////////////////////////////////////////////////////
// 產品接口角色 
interface IProduct {  
    public void productMethod();  
}  
// 產品實現 1 
class Product1 implements IProduct {  
    public void productMethod() {  
        System.out.println("產品1");  
    }  
}  
// 產品實現 2 
class Product2 implements IProduct {  
    public void productMethod() {  
        System.out.println("產品2");  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 工廠接口角色   
interface IFactory {  
    public IProduct createProduct();  
}  
// 工廠 1  
class Factory1 implements IFactory {  
    public IProduct createProduct() {  
        return new Product1();  
    }  
}  
// 工廠 2 
class Factory2 implements IFactory {  
    public IProduct createProduct() {  
        return new Product2();  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 測試
public class Client {  
    public static void main(String[] args) {  
        IFactory factory = new Factory1();  
        IProduct prodect = factory.createProduct();  
        prodect.productMethod();  
    }  
}  

建造者模式

在這裏插入圖片描述

#include <iostream>
#include <vector>
#include <string>
 
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////////
// 產品類 
class Product
{
    vector<string> parts;           // 動態數組
public:
    void Add(const string part)
    {
        parts.push_back(part);
    }
    void Show()const
    {
        for(int i = 0 ; i < parts.size() ; i++)
        {
            cout<<parts[i]<<endl;
        }
    }
};

//////////////////////////////////////////////////////////////////////////////////////////
// 抽象建造者
class Builder
{
public:
    ///////////////////////////////////////////////////////////////
    // 組裝過程 
    virtual void BuildHead() = 0;
    virtual void BuildBody() = 0;
    virtual void BuildHand() = 0;
    virtual void BuildFeet() = 0;
    virtual Product GetResult() = 0; 
};
//具體建造類:胖人
class FatPersonBuilder :public Builder
{
private:
    Product product;
public:
    //////////////////////////////////////////////////////////////
    // 組裝過程
    virtual void BuildHead()
    {
        product.Add("胖人頭");//創建胖人的頭
    }
    virtual void BuildBody()
    {
        product.Add("胖人身體");//創建胖人的身體
    }
    virtual void BuildHand()
    {
        product.Add("胖人手");//創建胖人的手
    }
    virtual void BuildFeet()
    {
        product.Add("胖人腳");//創建胖人的腳
    }
    /////////////////////////////////////////////////////////////
    // 獲得產品
    virtual Product GetResult()
    {
        return product;
    }
};
//具體建造類:瘦人
class ThinPersonBuilder :public Builder
{
private:
    Product product;
public:
    //////////////////////////////////////////////////////////////
    // 組裝過程
    virtual void BuildHead()
    {
        product.Add("瘦人人頭");//創建瘦人的頭
    }
    virtual void BuildBody()
    {
        product.Add("瘦人身體");//創建瘦人的身體
    }
    virtual void BuildHand()
    {
        product.Add("瘦人手");//創建瘦人的手
    }
    virtual void BuildFeet()
    {
        product.Add("瘦人腳");//創建瘦人的腳
    }
    /////////////////////////////////////////////////////////////
    // 獲得產品
    virtual Product GetResult()
    {
        return product;
    }
};
/////////////////////////////////////////////////////////////////////////////////////////
// 導演類
class Director
{
public:
    void Construct(Builder &builder)
    {
        builder.BuildHead();
        builder.BuildBody();
        builder.BuildHand();
        builder.BuildFeet();
    }
};
/////////////////////////////////////////////////////////////////////////////////////////
// 測試 
int main()
{
    Director *director = new Director();
    Builder *b1 = new FatPersonBuilder();
    Builder *b2 = new ThinPersonBuilder();

    // 通過導演類按指定步驟組裝
    director->Construct(*b1);
    // 通過建造類獲得產品
    Product p1 = b1->GetResult();
    p1.Show(); 
    return 0;
}

原型模式

在這裏插入圖片描述

/////////////////////////////////////////////////////////////////////////////////////////
// 原型類 
public class Prototype implements Cloneable {  
    private ArrayList list = new ArrayList();  
    public Prototype clone(){  
        Prototype prototype = null;  
        try{  
            prototype = (Prototype)super.clone();  
            prototype.list = (ArrayList) this.list.clone();  // 注意深,淺拷貝:ArrayList不是基本類型,所以成員變量list,不會被拷貝,需要我們自己實現深拷貝
        }catch(CloneNotSupportedException e){  
            e.printStackTrace();  
        }  
        return prototype;   
    }  
}
/////////////////////////////////////////////////////////////////////////////////////////
// 原型類實現
class ConcretePrototype extends Prototype{
    public void show(){
        System.out.println("原型模式實現類");
    }
}
/////////////////////////////////////////////////////////////////////////////////////////
// 調用類
public class Client {
    public static void main(String[] args){
        ConcretePrototype cp = new ConcretePrototype();

        for(int i=0; i< 10; i++){
            ConcretePrototype clonecp = (ConcretePrototype)cp.clone();// 關鍵在這個 clone() 函數,子類是沒有實現的,是父類實現的
            clonecp.show();
        }
    }
}

結構型

備忘錄模式

在這裏插入圖片描述

單記錄:

//////////////////////////////////////////////////////////////////////////////////////
// 發起人角色:需要被備份的類
class Originator {  
    ////////////////////////////////////////////
    // 需要備份的數據
    private String state = "";  
      
    public String getState() {  
        return state;  
    }  
    public void setState(String state) {  
        this.state = state;  
    }  
    // 創建備忘錄 
    public Memento createMemento(){  
        // 以當前狀態創建了備忘錄實例
        return new Memento(this.state);  
    }  
    // 恢復備忘錄 
    public void restoreMemento(Memento memento){  
        // 從備忘錄實例中恢復狀態
        this.setState(memento.getState());  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 備忘錄角色:保存所有需要備份的數據
class Memento {  
    //////////////////////////////////////////
    // 備份數據保存的地方
    private String state = "";  

    public Memento(String state){  
        this.state = state;  
    }  
    public String getState() {  
        return state;  
    }  
    public void setState(String state) {  
        this.state = state;  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 管理者角色:管理備忘錄實例的
class Caretaker {  
    //////////////////////////////////////
    // 備忘錄保存的地方
    private Memento memento;  


    public Memento getMemento(){  
        return memento;  
    }  
    public void setMemento(Memento memento){  
        this.memento = memento;  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 測試
public class Client {  
    public static void main(String[] args){  
        // 初始化發起人狀態
        Originator originator = new Originator();  
        originator.setState("狀態1");  
        System.out.println("初始狀態:"+originator.getState());  

        // 初始化管理者備份
        Caretaker caretaker = new Caretaker();  
        caretaker.setMemento(originator.createMemento()); // 管理者管理備份錄角色

        // 修改發起人狀態
        originator.setState("狀態2");  
        System.out.println("改變後狀態:"+originator.getState());  

        // 通過管理者獲得備忘錄實例,恢復發起者狀態
        originator.restoreMemento(caretaker.getMemento());  
        System.out.println("恢復後狀態:"+originator.getState());  
    }  
}  

多記錄:

//////////////////////////////////////////////////////////////////////////////////////
// 發起人角色:需要被備份的類
class Originator {  

    ///////////////////////////////////////////////
    // 要被保存的數據
    private String state1 = "";  
    private String state2 = "";  
    private String state3 = "";  
  
    public String getState1() {  
        return state1;  
    }  
    public void setState1(String state1) {  
        this.state1 = state1;  
    }  
    public String getState2() {  
        return state2;  
    }  
    public void setState2(String state2) {  
        this.state2 = state2;  
    }  
    public String getState3() {  
        return state3;  
    }  
    public void setState3(String state3) {  
        this.state3 = state3;  
    }  
    // 創建備忘錄
    public Memento createMemento(){  
        // 將要被保存的數據保存到備忘錄中
        return new Memento(BeanUtils.backupProp(this));  
    }  
    // 從備忘錄恢復  
    public void restoreMemento(Memento memento){  
        // 從備忘錄中恢復被保存的數據
        BeanUtils.restoreProp(this, memento.getStateMap());  
    }  
    public String toString(){  
        return "state1="+state1+"state2="+state2+"state3="+state3;  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 備忘錄角色:保存所有需要備份的數據
class Memento {  
    // 保存多個屬性值
    private Map<String, Object> stateMap;  
      
    public Memento(Map<String, Object> map){  
        this.stateMap = map;  
    }  
  
    // 獲得保存的數據
    public Map<String, Object> getStateMap() {  
        return stateMap;  
    }  
    // 存儲保存的數據
    public void setStateMap(Map<String, Object> stateMap) {  
        this.stateMap = stateMap;  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 備份工具:將多個屬性保存到 Map 中 或恢復
class BeanUtils {  
    // 保存內容到備忘錄
    public static Map<String, Object> backupProp(Object bean){  
        Map<String, Object> result = new HashMap<String, Object>();  
        try{  
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());  
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();  
            for(PropertyDescriptor des: descriptors){  
                String fieldName = des.getName();  
                Method getter = des.getReadMethod();  
                Object fieldValue = getter.invoke(bean, new Object[]{});  
                if(!fieldName.equalsIgnoreCase("class")){  
                    result.put(fieldName, fieldValue);  
                }  
            }  
              
        }catch(Exception e){  
            e.printStackTrace();  
        }  
        return result;  
    }  
    // 從備忘錄恢復內容  
    public static void restoreProp(Object bean, Map<String, Object> propMap){  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());  
            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();  
            for(PropertyDescriptor des: descriptors){  
                String fieldName = des.getName();  
                if(propMap.containsKey(fieldName)){  
                    Method setter = des.getWriteMethod();  
                    setter.invoke(bean, new Object[]{propMap.get(fieldName)});  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 管理者角色:管理備忘錄實例的
class Caretaker {  
    // 保存多個備忘錄
    private Map<String, Memento> memMap = new HashMap<String, Memento>();  

    // 獲得備忘錄 
    public Memento getMemento(String index){  
        return memMap.get(index);  
    }  
    // 保存備忘錄  
    public void setMemento(String index, Memento memento){  
        this.memMap.put(index, memento);  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////
// 測試 
class Client {  
    public static void main(String[] args){  
        // 初始化發起者狀態
        Originator ori = new Originator();  
        ori.setState1("中國");  
        ori.setState2("強盛");  
        ori.setState3("繁榮");  
        System.out.println("===初始化狀態===\n"+ori);  

        // 創建管理者
        Caretaker caretaker = new Caretaker();  
        caretaker.setMemento("001",ori.createMemento());  // 發起者創建備忘錄保存到管理者中 

        // 更改發起者狀態
        ori.setState1("軟件");  
        ori.setState2("架構");  
        ori.setState3("優秀");  
        System.out.println("===修改後狀態===\n"+ori);  
          
        // 通過管理者恢復備份的數據  
        ori.restoreMemento(caretaker.getMemento("001"));  
        System.out.println("===恢復後狀態===\n"+ori);  
    }  
}  

策略模式

在這裏插入圖片描述

///////////////////////////////////////////////////////////////////////////////////
// 抽象策略
interface IStrategy {  
    public void doSomething();  
}  

// 具體策略 1
class ConcreteStrategy1 implements IStrategy {  
    public void doSomething() {  
        System.out.println("具體策略1");  
    }  
}  

// 具體策略 2
class ConcreteStrategy2 implements IStrategy {  
    public void doSomething() {  
        System.out.println("具體策略2");  
    }  
}  

///////////////////////////////////////////////////////////////////////////////////////
// 封裝類:也叫上下文,對策略進行二次封裝,目的是避免高層模塊對策略的直接調用
class Context {  
    // 指向具體的策略
    private IStrategy strategy;  
      
    public Context(IStrategy strategy){  
        this.strategy = strategy;  
    }  
      
    public void execute(){  
        strategy.doSomething();  
    }  
}  
///////////////////////////////////////////////////////////////////////////////////////
// 測試  
public class Client {  
    public static void main(String[] args){  
        /* 使用策略類來調用封裝類 */
        Context context;  

        // 以具體策略 1 設置封裝類
        System.out.println("-----執行策略1-----");  
        context = new Context(new ConcreteStrategy1());  
        context.execute();  
  
        // 以具體策略 2 設置封裝類
        System.out.println("-----執行策略2-----");  
        context = new Context(new ConcreteStrategy2());  
        context.execute();  
    }  
}  

迭代器模式

在這裏插入圖片描述

// 定義:提供一種方法訪問一個容器對象中各個元素,而又不暴露該對象的內部細節。
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象迭代器:(Iterator)
        定義遍歷元素所需要的方法,一般來說會有這麼三個方法:取得第一個元素的方法first(),取得下一個元素
    的方法next(),判斷是否遍歷結束的方法isDone()(或者叫hasNext()),移出當前對象的方法remove(),*/
interface Iterator {  
    public Object next();       // 迭代到下一個
    public boolean hasNext();   // 判斷是否有下一個
}  
/* 迭代器實現: (ConcreteIterator)
        實現迭代器接口中定義的方法,完成集合的迭代。*/
class ConcreteIterator implements Iterator{  
    
    // 用來保存容器中數據
    private List list = new ArrayList();  
    private int cursor = 0;      // 遊標
    public ConcreteIterator(List list){  
        this.list = list;  
    }  
    public boolean hasNext() {  
        if(cursor==list.size()){  
            return false;  
        }  
        return true;  
    }  
    public Object next() {  
        Object obj = null;  
        if(this.hasNext()){  
            obj = this.list.get(cursor++);  
        }  
        return obj;  
    }  
}  
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象容器: (Aggregate)
        一般是一個接口,提供一個iterator()方法,例如java中的Collection接口,List接口,Set接口等。*/
interface Aggregate {  
    public void add(Object obj);  
    public void remove(Object obj);  
    
    // 依賴 關係
    public Iterator iterator();  
}  

/* 具體容器:(ConcreteAggregate)
        就是抽象容器的具體實現類,比如List接口的有序列表實現ArrayList,List接口的鏈表實現LinkList,Set
    接口的哈希列表的實現HashSet等。*/
class ConcreteAggregate implements Aggregate {  
    // 容量裏面的數據
    private List list = new ArrayList();  
    
    
    public void add(Object obj) {  
        list.add(obj);  
    }  
    public void remove(Object obj) {  
        list.remove(obj);  
    }  
  
    // 將容量裏面的數據傳給迭代器
    public Iterator iterator() {  
        // 這是具體的迭代器實例
        return new ConcreteIterator(list);  
    }  
  
    
}  
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 客戶
public class Client {  
    public static void main(String[] args){  
        // 創建容器並添加數據
        Aggregate ag = new ConcreteAggregate();  
        ag.add("小明");  
        ag.add("小紅");  
        ag.add("小剛");  

        // 初始化一個迭代器,即將容器裏面的數據傳給迭代器了
        Iterator it = ag.iterator();  

        // 迭代
        while(it.hasNext()){  
            // 從迭代器獲得數據
            String str = (String)it.next();  // next 函數迭代的是遊標 cursor++,即迭代器內部數據迭加
            System.out.println(str);  
        }  
    }  
} 

訪問者模式

在這裏插入圖片描述

///////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  抽象訪問者類: (Visitor)
    抽象類或者接口,聲明訪問者可以訪問哪些元素,具體到程序中就是visit方法中的參數定義哪些對象是可以被訪問的。*/
interface IVisitor {  
    public void visit(ConcreteElement1 el1);  
    public void visit(ConcreteElement2 el2);  
}  
/* 具體訪問者: (ConcreteVisitor)
    實現抽象訪問者所聲明的方法,它影響到訪問者訪問到一個類後該幹什麼,要做什麼事情。*/
class Visitor implements IVisitor {  
    
    // 調用具體元素 1 函數
    public void visit(ConcreteElement1 el1) {  
        el1.doSomething();  
    }  
    // 調用具體元素 2 函數  
    public void visit(ConcreteElement2 el2) {  
        el2.doSomething();  
    }  
}  

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 抽象元素類: (Element)
        接口或者抽象類,聲明接受哪一類訪問者訪問,程序上是通過accept方法中的參數來定義的。抽象元素一
    般有兩類方法,一部分是本身的業務邏輯,另外就是允許接收哪類訪問者來訪問。*/
abstract class Element {  
    // 調用訪問者類的 visit() 訪問本元素的 doSomething(),即 accept() --> 訪問者
    public abstract void accept(IVisitor visitor);  
    
    // 元素類特定
    public abstract void doSomething();  
}  
  
/* 具體元素類 1: (ConcreteElement)
    實現抽象元素類所聲明的accept方法,通常都是visitor.visit(this),基本上已經形成一種定式了 */  
class ConcreteElement1 extends Element {  
    public void accept(IVisitor visitor) {  
        visitor.visit(this);  
    }  

    public void doSomething(){  
        System.out.println("這是元素1");  
    }  
}  
/* 具體元素類 2:  (ConcreteElement)
    實現抽象元素類所聲明的accept方法,通常都是visitor.visit(this),基本上已經形成一種定式了 */  
class ConcreteElement2 extends Element { 
    public void accept(IVisitor visitor) {  
        visitor.visit(this);  
    }  
 
    public void doSomething(){  
        System.out.println("這是元素2");  
    }  
}  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 結構對象: (ObjectStruture)
    一個元素的容器,一般包含一個容納多個不同類、不同接口的容器,如 List、Set、Map 等,在項目中一般很少抽象出這個角色。*/  
class ObjectStruture {  
    // 獲得元素類鏈表
    public static List<Element> getList(){  

        // 一個元素類鏈表
        List<Element> list = new ArrayList<Element>();  

        // 隨機往裏面添加元素 1 或元素 2
        Random ran = new Random();  
        
        for(int i=0; i<10; i++){  
            int a = ran.nextInt(100);  
            if(a>50){  
                list.add(new ConcreteElement1());  
            }else{  
                list.add(new ConcreteElement2());  
            }  
        }  
        return list;  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// 調用類 (Client)
public class Client {  
    public static void main(String[] args){  
        // 一個元素類鏈表,通過 ObjectStruture.getList() 初始化 
        List<Element> list = ObjectStruture.getList();  

        // 遍歷元素類鏈表
        for(Element e: list){  
            e.accept(new Visitor());  // 經訪問者調用元素類本身操作函數,調用流程:元素類.accept() --> 訪問者類.visit() --> 元素類.doSomething()
        }  
    }  
}  

觀察者模式

在這裏插入圖片描述

Java API :

/* 簡單例子:
		購房者都關注着房子的價格變化,每當房子價格變化時,所有的購房者都
	可以觀察得到,實現上以上的購房者都屬於觀察者。

觀察者模式實現:
		在 java.util 包中提供了 Observable 類和 Observer 接口,使用它們即可完成
	觀察者模式。需要被觀察的類必須繼承 Observable 類,Observable 類的常用方法如
	表 11-17 所示:
		public void addObserver(Observer o) 		添加一個觀察者
		public void deleteObserver(Observer o)		刪除一個觀察者
		protected void setChanged()					被觀察者狀態發生改變
		public void notifyObservers(Object o)		通知所有觀察者狀態改變 

		然後每一個觀察者都需要實現 Observer 接口,Observer 接口定義如下:
		public interface Observer{
			void update(Observable o, Object arg);
		} */

import java.util.* ;
// 被觀察者 
class House extends Observable{				// 表示房子可以被觀察
	private float price ;					// 價錢
	public House(float price){
		this.price = price ;
	}
	public float getPrice(){
		return this.price ;
	}
	public void setPrice(float price){
		// 每一次修改的時候都應該引起觀察者的注意
		super.setChanged() ;				// 設置變化點
		super.notifyObservers(price) ;		// 價格被改變
		this.price = price ;
	}
	public String toString(){
		return "房子價格爲:" + this.price ;
	}
}; 

// 觀察者
class HousePriceObserver implements Observer{
	private String name ;
	public HousePriceObserver(String name){	// 設置每一個購房者的名字
		this.name = name ;
	}
	// 被觀察者變動時調用的函數 
	public void update(Observable o,Object arg){
		if(arg instanceof Float){
			System.out.print(this.name + "觀察到價格更改爲:") ;
			System.out.println(((Float)arg).floatValue()) ;
		}
	}
};
// 測試
public class ObserDemo01{
	public static void main(String args[]){
		House h = new House(1000000) ;
		HousePriceObserver hpo1 = new HousePriceObserver("購房者A") ;
		HousePriceObserver hpo2 = new HousePriceObserver("購房者B") ;
		HousePriceObserver hpo3 = new HousePriceObserver("購房者C") ;
		h.addObserver(hpo1) ;
		h.addObserver(hpo2) ;
		h.addObserver(hpo3) ;
		System.out.println(h) ;	// 輸出房子價格
		h.setPrice(666666) ;	// 修改房子價格
		System.out.println(h) ;	// 輸出房子價格
	}
};

自己實現:

//////////////////////////////////////////////////////////////////////////////
// 被觀察者抽象角色
abstract class Subject {  
    // 被觀察者列表
    private Vector<Observer> obs = new Vector<Observer>();  
      
    public void addObserver(Observer obs){  
        this.obs.add(obs);  
    }  
    public void delObserver(Observer obs){  
        this.obs.remove(obs);  
    }  
    protected void notifyObserver(){  
        // 遍歷觀察者列表,調用其 update()
        for(Observer o: obs){  
            o.update();  
        }  
    }  
    public abstract void doSomething();  
}  
// 具體被觀察者角色  
class ConcreteSubject extends Subject {  
    public void doSomething(){  
        System.out.println("被觀察者事件反生");  
        this.notifyObserver();  
    }  
}  

//////////////////////////////////////////////////////////////////////////////
// 抽象觀察者角色
interface Observer {  
    public void update();  
}  
// 具體觀察者角色 
class ConcreteObserver1 implements Observer {  
    public void update() {  
        System.out.println("觀察者1收到信息,並進行處理。");  
    }  
}  
// 具體觀察者角色 
class ConcreteObserver2 implements Observer {  
    public void update() {  
        System.out.println("觀察者2收到信息,並進行處理。");  
    }  
}  
//////////////////////////////////////////////////////////////////////////////
// 測試  
public class Client {  
    public static void main(String[] args){  
        Subject sub = new ConcreteSubject();  
        sub.addObserver(new ConcreteObserver1()); //添加觀察者1  
        sub.addObserver(new ConcreteObserver2()); //添加觀察者2  

        // 手動觸發被觀察事件
        sub.doSomething();  
    }  
}  

/* 
運行結果
    被觀察者事件反生
    觀察者1收到信息,並進行處理。
    觀察者2收到信息,並進行處理。
*/

解釋器模式

在這裏插入圖片描述

/*
例:
    R1 = 100
    R2 = 200
    R= R1 + R2
*/
//////////////////////////////////////////////////////////////////////////
//上下文(環境)角色,使用 HashMap 來存儲變量對應的數值,如 R= R1+R2,R1,R2 的值就保存在這裏 
class Context{
    //////////////////////////////////////
    // 用來保存參與計算的變量的值
    private Map valueMap = new HashMap();
    public void addValue(Variable x , int y){
        Integer yi = new Integer(y);
        valueMap.put(x , yi);
    }
    public int LookupValue(Variable x){
        int i = ((Integer)valueMap.get(x)).intValue();
    return i ;
    }
}
///////////////////////////////////////////////////////////////////////////
//抽象表達式角色,也可以用接口來實現
abstract class Expression{
    // 統一的運算接口
    public abstract int interpret(Context con);
}
///////////////////////////////////////////////////////////////////////////
//終結符表達式角色:常量
class Constant extends Expression{
    /////////////////////////////
    // 保存常量的值
    private int i ;
    public Constant(int i){
        this.i = i;
    }
    public int interpret(Context con){
        return i ;
    }
}
//終結符表達式角色:變量 
class Variable extends Expression{
    public int interpret(Context con) {
        //this 爲調用 interpret 方法的 Variable 對象
        return con.LookupValue(this);
    }
}
/////////////////////////////////////////////////////////////////////////////
//非終結符表達式角色
// 加 
class Add extends Expression{
    // 指向左,右表達式
    private Expression left ,right ;
    public Add(Expression left , Expression right) {
        this.left = left ;
        this.right= right ;
    }
    public int interpret(Context con){
        return left.interpret(con) + right.interpret(con);
    }
}
// 減
class Subtract extends Expression{
    // 指向左,右表達式
    private Expression left , right ;

    public Subtract(Expression left , Expression right) {
        this.left = left ;
        this.right= right ;
    }
    public int interpret(Context con){
        return left.interpret(con) - right.interpret(con);
    }
}
// 乘
class Multiply extends Expression{
    // 指向左,右表達式
    private Expression left , right ;
    public Multiply(Expression left , Expression right){
        this.left = left ;
        this.right= right ;
    }
    public int interpret(Context con){
        return left.interpret(con) * right.interpret(con);
    }
}
// 除
class Division extends Expression{
    // 指向左,右表達式
    private Expression left , right ;
    public Division(Expression left , Expression right){
        this.left = left ;
        this.right= right ;
    }
    public int interpret(Context con){
        try{
            return left.interpret(con) / right.interpret(con);
        }catch(ArithmeticException ae) {
            System.out.println("被除數爲 0! ");
            return -11111;
        }
    }
}
//////////////////////////////////////////////////////////////////////////////////
//測試程序,計算 (a*b)/(a-b+2)
public class Test
{
    private static Expression ex ;
    private static Context con ;
    public static void main(String[] args){
        // 上下文實例化
        con = new Context();

        //設置變量、常量
        Variable a = new Variable();
        Variable b = new Variable();
        // 設置常量
        Constant c = new Constant(2);

        //爲變量賦值
        con.addValue(a , 5);
        con.addValue(b , 7);

        //運算【對句子的結構由我們自己來分析,構造,這裏省事就不解析構造了,直接運算】
        ex = new Division(new Multiply(a , b), new Add(new Subtract(a , b) , c));
        System.out.println("運算結果爲: "+ex.interpret(con));
    }
}

命令模式

在這裏插入圖片描述

//////////////////////////////////////////////////////////////
// 命令接收者相關類:
//抽象接收者,定義了每個接收者應該完成的業務邏輯  
abstract class AbstractReceiver {  
    public abstract void doJob();  
}  
 
// 具體接收者01,實現自己真正的業務邏輯  
class Receiver01 extends AbstractReceiver {  
    public void doJob() {  
        System.out.println("接收者01 完成工作 ...\n");  
    }  
}  
 
// 具體接收者02,實現自己真正的業務邏輯  
class Receiver02 extends AbstractReceiver {  
    public void doJob() {  
        System.out.println("接收者02 完成工作 ...\n");  
    }  
} 
//////////////////////////////////////////////////////////////
// 命令類:
// 抽象命令類,定義了每個具體命令被執行的入口方法execute()  
abstract class AbstractCommand {  
    public abstract void execute();  
}  
 
// 具體命令類01,通過構造函數的參數決定了該命令由哪個接收者執行  
class Command01 extends AbstsractCommand {  
    private AbstractReceiver receiver = null;  
 
    public Command01(AbstractReceiver receiver) {  
        this.receiver = receiver;  
    }  
 
    public void execute() {  
              System.out.println("命令01 被髮布 ...");  
        this.receiver.doJob();  
    }  
}  
 
// 具體命令類02,通過構造函數的參數決定了該命令由哪個接收者執行  
class Command02 extends AbstractCommand {  
    private AbstractReceiver receiver = null;  
 
    public Command02(AbstractReceiver receiver) {  
        this.receiver = receiver;  
    }  
 
    public void execute() {  
              System.out.println("命令02 被髮布 ...");  
        this.receiver.doJob();  
    }  
} 
//////////////////////////////////////////////////////////
// 調用者類:
// 調用者,負責將具體的命令傳送給具體的接收者  
class Invoker {  
    private AbstractCommand command = null;  
 
    public void setCommand(AbstractCommand command) {  
        this.command = command;  
    }  
 
    public void action() {  
        this.command.execute();  
    }  
} 

///////////////////////////////////////////////////////////
// 測試類:
//測試類  
public class Client {  
    public static void main(String[] args) {  
        // 創建調用者  
        Invoker invoker = new Invoker();  
 
        // 創建一個具體命令,並指定該命令被執行的具體接收者  
        AbstractCommand command01 = new Command01(new Receiver01());  
 
        // 給調用者發佈一個具體命令  
        invoker.setCommand(command01);  
 
        // 調用者執行命令,其實是將其傳送給具體的接收者並讓其真正執行  
        invoker.action();  
          
        AbstractCommand command02 = new Command01(new Receiver02());  
        invoker.setCommand(command02);  
        invoker.action();  
    }  
} 



/* 
測試結果:
    命令01 被髮布 ...
    接收者01 完成工作 ...
     
    命令02 被髮布 ...
    接收者02 完成工作 ...

        如上面測試中輸出的結果,我們知道在客戶端中每次聲明並創建一個具體的命令對象時總要顯式地將
    其指定給某一具體的接收者(也就是命令的最終執行者),這似乎不太靈活,在現實中有些命令的發佈也
    確實不是預先就指定了該命令的接收者的。
*/

    ////////////////////////////////////////////////////////////////
    // 命令類:
    /*  
     * 抽象命令類,使用構造函數的傳入參數預先內定具體接收者, 若想使用其他接收者,可在子類的構造函數中傳入  
     */ 
    abstract class AbstractCommand {  
        protected AbstractReceiver receiver = null;  
     
        public AbstractCommand(AbstractReceiver receiver) {  
            this.receiver = receiver;  
        }  
     
        public abstract void execute();  
    }  
     
    // 具體命令類01,提供無參、有參兩種構造函數  
    class Command01 extends AbstractCommand {  
     
        // 使用無參構造函數來默認使用的具體接收者  
        public Command01() {  
            super(new Receiver01());  
        }  
     
        // 使用有參構造函數來指定具體的接收者  
        public Command01(AbstractReceiver receiver) {  
            super(receiver);  
        }  
     
        public void execute() {  
                  System.out.println("命令01 被髮布 ...")  
            this.receiver.doJob();  
        }  
    }  
     
    // 具體命令類02,提供無參、有參兩種構造函數  
    class Command02 extends AbstractCommand {  
     
        // 使用無參構造函數來默認使用的具體接收者  
        public Command02() {  
            super(new Receiver02());  
        }  
     
        // 使用有參構造函數來指定具體的接收者  
        public Command02(AbstractReceiver receiver) {  
            super(receiver);  
        }  
     
        public void execute() {  
                  System.out.println("命令02 被髮布 ...")  
            this.receiver.doJob();  
        }  
    } 

    //////////////////////////////////////////////////////////////////////////////////////
    // 修改後的測試類:
    // 測試類  
    public class Client {  
        public static void main(String[] args) {  
            // 創建調用者  
            Invoker invoker = new Invoker();  
     
            // 創建一個具體命令,並指定該命令被執行的具體接收者  
    //      AbstractCommand command01 = new Command01(new Receiver01());  
            AbstractCommand command01 = new Command01();  
     
            // 給調用者發佈一個具體命令  
            invoker.setCommand(command01);  
     
            // 調用者執行命令,其實是將其傳送給具體的接收者並讓其真正執行  
            invoker.action();  
              
    //      AbstractCommand command02 = new Command01(receiver02);  
            AbstractCommand command02 = new Command02();  
            invoker.setCommand(command02);  
            invoker.action();  
              
            System.out.println("\n設置命令01由接收者02執行...");  
            command01 = new Command01(new Receiver02());  
            invoker.setCommand(command01);  
            invoker.action();  
        }  
    } 

    /*
    測試結果:
            命令01 被髮布 ...
            接收者01 完成工作 ...
             
            命令02 被髮布 ...
            接收者02 完成工作 ...
             
            設置命令01由接收者02執行...
            命令01 被髮布 ...
            接收者02 完成工作 ...
    */

通用類型:

// 客戶端中每次聲明並創建一個具體的命令對象時總要顯式地將其指定給某一具體的接收者(也就是命令的最終執行者)
//////////////////////////////////////////////////////////////
// 命令接收者相關類:
//抽象接收者,定義了每個接收者應該完成的業務邏輯  
abstract class AbstractReceiver {  
    public abstract void doJob();  
}  
 
// 具體接收者01,實現自己真正的業務邏輯  
class Receiver01 extends AbstractReceiver {  
    public void doJob() {  
        System.out.println("接收者01 完成工作 ...\n");  
    }  
}  
 
// 具體接收者02,實現自己真正的業務邏輯  
class Receiver02 extends AbstractReceiver {  
    public void doJob() {  
        System.out.println("接收者02 完成工作 ...\n");  
    }  
} 
//////////////////////////////////////////////////////////////
// 命令類:
// 抽象命令類,定義了每個具體命令被執行的入口方法execute()  
abstract class AbstractCommand {  
    public abstract void execute();  
}  
 
// 具體命令類01,通過構造函數的參數決定了該命令由哪個接收者執行  
class Command01 extends AbstsractCommand {  
    private AbstractReceiver receiver = null;  
 
    public Command01(AbstractReceiver receiver) {  
        this.receiver = receiver;  
    }  
 
    public void execute() {  
              System.out.println("命令01 被髮布 ...");  
        this.receiver.doJob();  
    }  
}  
 
// 具體命令類02,通過構造函數的參數決定了該命令由哪個接收者執行  
class Command02 extends AbstractCommand {  
    private AbstractReceiver receiver = null;  
 
    public Command02(AbstractReceiver receiver) {  
        this.receiver = receiver;  
    }  
 
    public void execute() {  
              System.out.println("命令02 被髮布 ...");  
        this.receiver.doJob();  
    }  
} 
//////////////////////////////////////////////////////////
// 調用者類:
// 調用者,負責將具體的命令傳送給具體的接收者  
class Invoker {  
    // 指向要調用的命令
    private AbstractCommand command = null;  
 
    public void setCommand(AbstractCommand command) {  
        this.command = command;  
    }  
 
    public void action() {  
        this.command.execute();  
    }  
} 

///////////////////////////////////////////////////////////
// 測試類:
// 測試類  
public class Client {  
    public static void main(String[] args) {  
        // 創建調用者  
        Invoker invoker = new Invoker();  
 
        // 創建一個具體命令,並指定該命令被執行的具體接收者  
        AbstractCommand command01 = new Command01(new Receiver01());  // 【缺點:執行前就需要綁定命令類與執行者】
 
        // 給調用者發佈一個具體命令  
        invoker.setCommand(command01);  
 
        // 調用者執行命令,其實是將其傳送給具體的接收者並讓其真正執行  
        invoker.action();  
          
        AbstractCommand command02 = new Command01(new Receiver02());  
        invoker.setCommand(command02);  
        invoker.action();  
    }  
} 



/* 
測試結果:
    命令01 被髮布 ...
    接收者01 完成工作 ...
     
    命令02 被髮布 ...
    接收者02 完成工作 ...


*/

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* 
    如上面測試中輸出的結果,我們知道在客戶端中每次聲明並創建一個具體的命令對象時總要顯式地將
其指定給某一具體的接收者(也就是命令的最終執行者),這似乎不太靈活,在現實中有些命令的發佈也
確實不是預先就指定了該命令的接收者的。*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

修改類型:

// 不再需要客戶端中每次聲明並創建一個具體的命令對象時總要顯式地將其指定給某一具體的接收者(也就是命令的最終執行者)
// 【而是在聲明時直接綁定了】。
/////////////////////////////////////////////////////////////
// 命令接收者相關類:
//抽象接收者,定義了每個接收者應該完成的業務邏輯  
abstract class AbstractReceiver {  
    public abstract void doJob();  
}  
 
// 具體接收者01,實現自己真正的業務邏輯  
class Receiver01 extends AbstractReceiver {  
    public void doJob() {  
        System.out.println("接收者01 完成工作 ...\n");  
    }  
}  
 
// 具體接收者02,實現自己真正的業務邏輯  
class Receiver02 extends AbstractReceiver {  
    public void doJob() {  
        System.out.println("接收者02 完成工作 ...\n");  
    }  
} 
//////////////////////////////////////////////////////////
// 調用者類:
// 調用者,負責將具體的命令傳送給具體的接收者  
class Invoker {  
    private AbstractCommand command = null;  
 
    public void setCommand(AbstractCommand command) {  
        this.command = command;  
    }  
 
    public void action() {  
        this.command.execute();  
    }  
} 

////////////////////////////////////////////////////////////////////////
// 修改後的命令類:
/*  
 * 抽象命令類,使用構造函數的傳入參數預先內定具體接收者, 若想使用其他接收者,可在子類的構造函數中傳入  
 */ 
abstract class AbstractCommand {  
    // 在抽象類定義了一個默認的接收者,這樣當有需要時再修改,否則直接繼承
    protected AbstractReceiver receiver = null;  
 
    public AbstractCommand(AbstractReceiver receiver) {  
        this.receiver = receiver;  
    }  
 
    public abstract void execute();  
}  
 
// 具體命令類01,提供無參、有參兩種構造函數  
class Command01 extends AbstractCommand {  
 
    //////////////////////////////////////////////////
    // 使用無參構造函數來默認使用的具體接收者  
    public Command01() {  
        super(new Receiver01());  
    }  
 
    ///////////////////////////////////////////////////
    // 使用有參構造函數來指定具體的接收者  
    public Command01(AbstractReceiver receiver) {  
        super(receiver);  
    }  
 
    public void execute() {  
              System.out.println("命令01 被髮布 ...")  
        this.receiver.doJob();  
    }  
}  
 
// 具體命令類02,提供無參、有參兩種構造函數  
class Command02 extends AbstractCommand {  
 
    // 使用無參構造函數來默認使用的具體接收者  
    public Command02() {  
        super(new Receiver02());  
    }  
 
    // 使用有參構造函數來指定具體的接收者  
    public Command02(AbstractReceiver receiver) {  
        super(receiver);  
    }  
 
    public void execute() {  
              System.out.println("命令02 被髮布 ...")  
        this.receiver.doJob();  
    }  
} 

//////////////////////////////////////////////////////////////////////////////////////
// 修改後的測試類:
// 測試類  
public class Client {  
    public static void main(String[] args) {  
        // 創建調用者  
        Invoker invoker = new Invoker();  
 
        // 創建一個具體命令,並指定該命令被執行的具體接收者  
//      AbstractCommand command01 = new Command01(new Receiver01());  
        AbstractCommand command01 = new Command01();  // 使用無參命令時會自己創建一個默認接收者
 
        // 給調用者發佈一個具體命令  
        invoker.setCommand(command01);  
 
        // 調用者執行命令,其實是將其傳送給具體的接收者並讓其真正執行  
        invoker.action();  
          
//      AbstractCommand command02 = new Command01(receiver02);  
        AbstractCommand command02 = new Command02();  
        invoker.setCommand(command02);  
        invoker.action();  
          
        System.out.println("\n設置命令01由接收者02執行...");  
        command01 = new Command01(new Receiver02());  
        invoker.setCommand(command01);  
        invoker.action();  
    }  
} 

/*
測試結果:
        命令01 被髮布 ...
        接收者01 完成工作 ...
         
        命令02 被髮布 ...
        接收者02 完成工作 ...
         
        設置命令01由接收者02執行...
        命令01 被髮布 ...
        接收者02 完成工作 ...
*/

模板方法模式

在這裏插入圖片描述

////////////////////////////////////////////////////////////////////////////////////////
// 抽象類 
abstract class AbstractSort {  
      
    /** 
     * 將數組array由小到大排序 
     * @param array 
     */  
    protected abstract void sort(int[] array);  // 父類定義好,子類去實現
      
    public void showSortResult(int[] array){  
        this.sort(array);  
        System.out.print("排序結果:");  
        for (int i = 0; i < array.length; i++){  
            System.out.printf("%3s", array[i]);  
        }  
    }  
}  
////////////////////////////////////////////////////////////////////////////////////////
// 實現類 
class ConcreteSort extends AbstractSort {  
  
    @Override  
    protected void sort(int[] array){  
        for(int i=0; i<array.length-1; i++){  
            selectSort(array, i);  
        }  
    }  
      
    private void selectSort(int[] array, int index) {  
        int MinValue = 32767; // 最小值變量  
        int indexMin = 0; // 最小值索引變量  
        int Temp; // 暫存變量  
        for (int i = index; i < array.length; i++) {  
            if (array[i] < MinValue){ // 找到最小值  
                MinValue = array[i]; // 儲存最小值  
                indexMin = i;   
            }  
        }  
        Temp = array[index]; // 交換兩數值  
        array[index] = array[indexMin];  
        array[indexMin] = Temp;  
    }  
}  
////////////////////////////////////////////////////////////////////////////////////////
// 測試 
public class Client {  
    public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 預設數據數組  
    public static void main(String[] args){  

        AbstractSort s = new ConcreteSort();  
        s.showSortResult(a);  
    }  
}  

/* 運行結果:
    排序結果:  0  1  3  4  5  7  9 10 12 32 */

責任鏈模式

在這裏插入圖片描述

// 任務優先級
class Level {  
    private int level = 0;  
    public Level(int level){  
        this.level = level;  
    };  
      
    public boolean above(Level level){  
        if(this.level >= level.level){  
            return true;  
        }  
        return false;  
    }  
}  
// 任請請求項  
class Request {  
    Level level;  
    public Request(Level level){  
        this.level = level;  
    }  
      
    public Level getLevel(){  
        return level;  
    }  
}  
// 處理結構項  
class Response {  
  
}  

/////////////////////////////////////////////////////////////////////////////////////////
// 抽象處理類  
abstract class Handler {  
    //////////////////////////////////////////////////
    // 這個類似一個對象鏈表,保存下一個對象
    private Handler nextHandler;      

    /////////////////////////////////////////////////
    // 調用責任鏈函數
    public final Response handleRequest(Request request){  
        Response response = null;  
          
        // 判斷當前對象的處理等級是否大於請求  
        if(this.getHandlerLevel().above(request.getLevel())){  
            // 用當前對象進行處理
            response = this.response(request);  
        }else{  
            if(this.nextHandler != null){  
                this.nextHandler.handleRequest(request);  
            }else{  
                System.out.println("-----沒有合適的處理器-----");  
            }  
        }  
        return response;  
    }  
    ///////////////////////////////////////////////
    // 設置責任鏈函數
    public void setNextHandler(Handler handler){  
        this.nextHandler = handler;  
    }  
    
    ///////////////////////////////////////////////
    // 設置子類必須有的實現的函數
    protected abstract Level getHandlerLevel();  
    public abstract Response response(Request request);  
}  

//////////////////////////////////////////////////////////////////////////////////////
// 具體處理類 1
class ConcreteHandler1 extends Handler {  
    protected Level getHandlerLevel() {  
        return new Level(1);  
    }  
    public Response response(Request request) {  
        System.out.println("-----請求由處理器1進行處理-----");  
        return null;  
    }  
}  
// 具體處理類 2  
class ConcreteHandler2 extends Handler {  
    protected Level getHandlerLevel() {  
        return new Level(3);  
    }  
    public Response response(Request request) {  
        System.out.println("-----請求由處理器2進行處理-----");  
        return null;  
    }  
}  
// 具體處理類 3  
class ConcreteHandler3 extends Handler {  
    protected Level getHandlerLevel() {  
        return new Level(5);  
    }  
    public Response response(Request request) {  
        System.out.println("-----請求由處理器3進行處理-----");  
        return null;  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////////////
// 測試  
public class Client {  
    public static void main(String[] args){  
        Handler handler1 = new ConcreteHandler1();  
        Handler handler2 = new ConcreteHandler2();  
        Handler handler3 = new ConcreteHandler3();  
  
        // 組成責任鏈
        handler1.setNextHandler(handler2);  
        handler2.setNextHandler(handler3);  
          
        // 調用責任鏈
        Response response = handler1.handleRequest(new Request(new Level(4)));  
    }  
}  

中介者模式

在這裏插入圖片描述

// 在中介者模式中,同事類之間必須通過中介者才能進行消息傳遞
/////////////////////////////////////////////////////////////////////////////////
// 抽象同事
abstract class AbstractColleague {  
    protected int number;  
  
    public int getNumber() {  
        return number;  
    }  
  
    public void setNumber(int number){  
        this.number = number;  
    }  
    //注意這裏的參數不再是同事類,而是一箇中介者 ,通過中介者影響同事 
    public abstract void setNumber(int number, AbstractMediator am);  
}  
  
// 具體同事 A  
class ColleagueA extends AbstractColleague{  
  
    public void setNumber(int number, AbstractMediator am) {  
        this.number = number;  
        am.AaffectB();  
    }  
}  
// 具體同事 B  
class ColleagueB extends AbstractColleague{  
  
    @Override  
    public void setNumber(int number, AbstractMediator am) {  
        this.number = number;  
        am.BaffectA();  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////
// 抽象中介者  
abstract class AbstractMediator {  

    // 兩個變量保存需要互相影響的具體同事類
    protected AbstractColleague A;  
    protected AbstractColleague B;  
      
    public AbstractMediator(AbstractColleague a, AbstractColleague b) {  
        A = a;  
        B = b;  
    }  
  
    public abstract void AaffectB();  
      
    public abstract void BaffectA();  
  
}  
// 具體中介者
class Mediator extends AbstractMediator {  
  
    public Mediator(AbstractColleague a, AbstractColleague b) {  
        super(a, b);  
    }  
  
    //處理A對B的影響  
    public void AaffectB() {  
        int number = A.getNumber();  
        B.setNumber(number*100);  
    }  
  
    //處理B對A的影響  
    public void BaffectA() {  
        int number = B.getNumber();  
        A.setNumber(number/100);  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////////
// 測試  
public class Client {  
    public static void main(String[] args){  
        // 創建同事 A,同事 B 
        AbstractColleague collA = new ColleagueA();  
        AbstractColleague collB = new ColleagueB();  
        
        // 設置一箇中介  
        AbstractMediator am = new Mediator(collA, collB);  
          
        // 同事通過中介互相影響
        System.out.println("==========通過設置A影響B==========");  
        collA.setNumber(1000, am);  
        System.out.println("collA的number值爲:"+collA.getNumber());  
        System.out.println("collB的number值爲A的10倍:"+collB.getNumber());  
  
        System.out.println("==========通過設置B影響A==========");  
        collB.setNumber(1000, am);  
        System.out.println("collB的number值爲:"+collB.getNumber());  
        System.out.println("collA的number值爲B的0.1倍:"+collA.getNumber());  
          
    }  
}  

狀態模式

在這裏插入圖片描述

//////////////////////////////////////////////////////////////////////////////////
/// Context類,維護一個ConcreteState子類的實例,這個實例定義當前的狀態。
public class Context
{
    // 表示當前狀態
    private State state;
    
    /// 定義Context的初始狀態
    /// <param name="state"></param>
    public Context(State state)
    {
        this.state = state;
    }
    
    /// 可讀寫的狀態屬性,用於讀取和設置新狀態
    public State State
    {
        get { return state; }
        set { state = value; }
    }
    
    /// 對請求做處理,並設置下一個狀態
    public void Request()
    {
        state.Handle(this);
    }
}

/////////////////////////////////////////////////////////////////////////////////////
/// 抽象狀態類,定義一個接口以封裝與Context的一個特定狀態相關的行爲
public abstract class State
{
    public abstract void Handle(Context context);
}

/// 具體狀態類 A, 每一個子類實現一個與Context的一個狀態相關的行爲
public class ConcreteStateA : State
{
    
    /// 設置ConcreteStateA的下一個狀態是ConcreteStateB
    /// <param name="context"></param>
    public override void Handle(Context context)
    {
        Console.WriteLine("當前狀態是 A.");
        context.State = new ConcreteStateB();
    }
}
/// 具體狀態類 B
public class ConcreteStateB : State
{
    
    /// 設置ConcreteStateB的下一個狀態是ConcreteSateA
    /// <param name="context"></param>
    public override void Handle(Context context)
    {
        Console.WriteLine("當前狀態是 B.");
        // 改變上下文當前狀態
        context.State = new ConcreteStateA();
    }
}
/////////////////////////////////////////////////////////////////////////////////////
// 測試 
class Program
   {
       static void Main(string[] args)
       {
           // 設置Context的初始狀態爲ConcreteStateA
           Context context = new Context(new ConcreteStateA());

           // 不斷地進行請求,同時更改狀態
           context.Request();
           context.Request();
           context.Request();
           context.Request();

           Console.Read();
       }
   }

行爲型

代理模式

在這裏插入圖片描述

//////////////////////////////////////////////////////////
// 目標接口: 代理角色與具體角色共通
interface Network{
	public void browse() ;	// 瀏覽
}
////////////////////////////////////////////////////////////
// 真實角色
class Real implements Network{
	public void browse(){
		System.out.println("上網瀏覽信息") ;
	}
};
////////////////////////////////////////////////////////////////
// 代理角色
class Proxy implements Network{
	////////////////////////////////////////
	// 這裏指向直實角色, 通過在函數中調用真實角色函數,實現代理
	private Network network ;	// 代理對象
	public Proxy(Network network){
		this.network = network ;
	}
	public void check(){
		System.out.println("檢查用戶是否合法。") ;
	}
	public void browse(){
		this.check() ;
		this.network.browse() ;	// 調用真實的主題操作
	}
};
//////////////////////////////////////////////////////////////////
// 測試
public class ProxyDemo{
	public static void main(String args[]){
		Network net = null ;
		net  = new Proxy(new Real()) ;//  指定代理操作
		net.browse() ;	// 客戶只關心上網瀏覽一個操作
	}
};

橋接模式

在這裏插入圖片描述

///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 抽象化角色 (Abstraction)
 * 它主要的職責是定義出該角色的行爲,同時保存一個對實現化角色的引用,該角色一般是抽象類。
 * @author Administrator
 * 
 */
public abstract class Abstraction {
 
    //////////////////////////////////////////////////////
    // 定義對實現化角色的引用
    private Implementor imp;
 
    // 約束子類必須實現該構造函數
    public Abstraction(Implementor _imp) {
        this.imp = _imp;
    }
 
    // 自身的行爲和屬性
    public void request() {
        this.imp.doSomething();
    }
 
    // 獲得實現化角色
    public Implementor getImp() {
        return this.imp;
    }
}

/**
 * 具體抽象化角色  (RefinedAbstraction)
 * 它引用實現化角色對抽象化角色進行修正。
 * @author Administrator
 * 
 */
public class RefinedAbstraction extends Abstraction {
 
    // 覆寫構造函數
    public RefinedAbstraction(Implementor _imp) {
        // 將具體的實現實例保存在父類中
        super(_imp);
    }
 
    /////////////////////////////////////////
    // 修正父類的行爲
    @Override
    public void request() {
        /*
         * 業務處理
         */
        super.request();

        // 這裏可以調用實現化角色的對象
        super.getImp().doAnything();
    }
 
}
//////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 實現化角色 (Implementor)
 * 它是接口或者抽象類,定義角色必須的行爲和屬性。
 * @author Administrator
 * 
 */
public interface Implementor {
 
    // 基本方法
    public void doSomething();
 
    public void doAnything();
 
}

/**
 * 具體實現化角色 1  (ConcreteImplementor1)
 * 它實現接口或抽象類定義的方法和屬性。
 * @author Administrator
 * 
 */
public class ConcreteImplementor1 implements Implementor {
 
    public void doAnything() {
        // 業務處理邏輯
    }
 
    public void doSomething() {
        // 業務處理邏輯
    }
 
}

/**
 * 具體實現化角色 2 (ConcreteImplementor2)
 * 它實現接口或抽象類定義的方法和屬性。
 * @author Administrator
 * 
 */
public class ConcreteImplementor2 implements Implementor {
 
    public void doAnything() {
        // 業務處理邏輯
    }
 
    public void doSomething() {
        // 業務處理邏輯
    }
 
}


////////////////////////////////////////////////////////////////////////////////////////////////////
// 測試 
public class Client {
 

    public static void main(String[] args) {
        // 定義一個實現化角色
        Implementor imp = new ConcreteImplementor1();
 
        // 定義一個抽象化角色, 並通過 RefinedAbstraction() 將實現化角色實例保存到父類中
        Abstraction abs = new RefinedAbstraction(imp);
 
        // 執行 RefinedAbstraction 類函數,通過上面的實現化角色實例,修正父類對應函數
        abs.request();
    }
 
}

適配器模式

在這裏插入圖片描述

類適配:

////////////////////////////////////////////////////////////////////////////////
// 被適配角色 
// 已存在的、具有特殊功能、但不符合我們既有的標準接口的類  
class Adaptee {  
    public void specificRequest() {  
        System.out.println("被適配類具有 特殊功能...");  
    }  
}  
//////////////////////////////////////////////////////////////////////////////  
// 抽象目村要求接口
// 目標接口,或稱爲標準接口  
interface Target {  
    public void request();  
}  
// 具體目標類,只提供普通功能  
class ConcreteTarget implements Target {  
    public void request() {  
        System.out.println("普通類 具有 普通功能...");  
    }  
}  
///////////////////////////////////////////////////////////////////////////////   
// 適配器類,繼承了被適配類,同時實現標準接口  
class Adapter extends Adaptee implements Target{  
    // extends:繼承的是被適配角色
    // implements: 繼承的是要適配的接口
    // 實現目標要求的接口,並在接口內調用被適配角色函數,實現適配
    public void request() { 
        // 調用被適配器類的函數,實現適配 
        super.specificRequest();  
    }  
}  
///////////////////////////////////////////////////////////////////////////////   
// 測試類public class Client {  
    public static void main(String[] args) {  
        // 使用普通功能類  
        Target concreteTarget = new ConcreteTarget();  
        concreteTarget.request();  
          
        // 使用特殊功能類,即適配類  
        Target adapter = new Adapter();  
        adapter.request();  
    }  
}  

對象適配:

////////////////////////////////////////////////////////////////////////////////
// 被適配角色 
// 已存在的、具有特殊功能、但不符合我們既有的標準接口的類  
class Adaptee {  
    public void specificRequest() {  
        System.out.println("被適配類具有 特殊功能...");  
    }  
}  
//////////////////////////////////////////////////////////////////////////////  
// 抽象目村要求接口
// 目標接口,或稱爲標準接口  
interface Target {  
    public void request();  
}  
// 具體目標類,只提供普通功能  
class ConcreteTarget implements Target {  
    public void request() {  
        System.out.println("普通類 具有 普通功能...");  
    }  
}  
//////////////////////////////////////////////////////////////////////////////////////////
// 適配器類,直接關聯被適配類,同時實現標準接口  
class Adapter implements Target{  
    // 直接關聯被適配類  
    private Adaptee adaptee;  
      
    // 可以通過構造函數傳入具體需要適配的被適配類對象  
    public Adapter (Adaptee adaptee) {  
        this.adaptee = adaptee;  
    }  
      
    public void request() {  
        // 這裏是使用委託的方式完成特殊功能  
        this.adaptee.specificRequest();  
    }  
}  

////////////////////////////////////////////////////////////////////////////////////////  
// 測試類  
public class Client {  
    public static void main(String[] args) {  
        // 使用普通功能類  
        Target concreteTarget = new ConcreteTarget();  
        concreteTarget.request();  
          
        // 使用特殊功能類,即適配類,  
        // 需要先創建一個被適配類的對象作爲參數  
        Target adapter = new Adapter(new Adaptee());  
        adapter.request();  
    }  
}  

外觀模式

在這裏插入圖片描述

外觀模式1:

package com.yeepay.sxf.template18;  

//////////////////////////////////////////////////////////////////////////////////////////////
/** 【1】寫信的業務類 
 * 寫信的業務類 
 * 隱藏在門面角色裏邊,不需要暴露太多 
 * @author sxf 
 * 
 */  
public interface  ILetterProcess {  
    //寫信的內容  
    public void writeContext(String context);  
    //寫信的地址  
    public void fillEnvelope(String address);  
    //將信裝入信封  
    public void letterInotoEnvelope();  
    //發送信件  
    public void sendLetter();  
}  
// 【2】寫信的業務類的實現
public class LetterProcessImpl  implements ILetterProcess{  
  
    @Override  
    public void writeContext(String context) {  
        System.out.println("LetterProcessImpl.writeContext()寫信的內容:"+context);  
    }  
  
    @Override  
    public void fillEnvelope(String address) {  
        // TODO Auto-generated method stub  
        System.out.println("LetterProcessImpl.fillEnvelope()寫信的郵寄地址:"+address);  
    }  
  
    @Override  
    public void letterInotoEnvelope() {  
        System.out.println("LetterProcessImpl.letterInotoEnvelope()將信裝入信封");  
    }  
  
    @Override  
    public void sendLetter() {  
        System.out.println("LetterProcessImpl.sendLetter()郵寄信");  
    }  
  
      
}  
/////////////////////////////////////////////////////////////////////////////////////////
/** 【3】寫信的業務類的門面角色
 * 寫信的門面角色 
 * 一個人想寫信,只需要給這個門面提供相應的參數,後續事件不用關心。 
 * @author sxf 
 * 
 */  
public class ModenPostOffce {  
  
    private ILetterProcess letterProcess;  
      
    public ModenPostOffce(ILetterProcess letterProcess){  
        this.letterProcess=letterProcess;  
    }  
      
    public void sendLetter(String context,String address){  
        //寫信  
        letterProcess.writeContext(context);  
        //寫地址  
        letterProcess.fillEnvelope(address);  
        //裝信封  
        letterProcess.letterInotoEnvelope();  
        //發送信件  
        letterProcess.sendLetter();  
    }  
}  
/////////////////////////////////////////////////////////////////////////////////////////
/** 【4】客戶端測試
 * 客戶端測試 
 * @author sxf 
 * 
 */  
public class ClientTest {  
  
    public static void main(String[] args) {  
        //寫信的業務類  
        ILetterProcess letterProcess=new LetterProcessImpl();  
        //寫信業務類的門面類  
        ModenPostOffce modenPostOffce=new ModenPostOffce(letterProcess);  
        //一個人員通過門面寫信  
        modenPostOffce.sendLetter("dddsdfdf", "cccccccccc");  
    }  
}  

外觀模式 2:

using System;
//////////////////////////////////////////////////////////////////////////////////
/* 外觀模式就是動裏不動外,讓外層好調用。*/

public class Camera
{
  public void TurnOn()
  {
    Console.WriteLine("Turning on the camera.");
  }

  public void TurnOff()
  {
    Console.WriteLine("Turning off the camera.");
  }

  public void Rotate(int degrees)
  {
    Console.WriteLine("Rotating the camera by {0} degrees.", degrees);
  }
}

public class Light
{

  public void TurnOff()
  {
    Console.WriteLine("Turning on the light.");
  }

  public void TurnOn()
  {
    Console.WriteLine("Turning off the light.");
  }

  public void ChangeBulb()
  {
    Console.WriteLine("changing the light-bulb.");
  }
}

public class Sensor
{
  public void Activate()
  {
    Console.WriteLine("Activating the sensor.");
  }

  public void Deactivate()
  {
    Console.WriteLine("Deactivating the sensor.");
  }

  public void Trigger()
  {
    Console.WriteLine("The sensor has triggered.");
  }
}

public class Alarm
{

  public void Activate()
  {
    Console.WriteLine("Activating the alarm.");
  }

  public void Deactivate()
  {
    Console.WriteLine("Deactivating the alarm.");
  }

  public void Ring()
  {
    Console.WriteLine("Ringing the alarm.");
  }

  public void StopRing()
  {
    Console.WriteLine("Stop the alarm.");
  }
}
//////////////////////////////////////////////////////////////////////////////////
/* 外觀類 */
public class SecurityFacade
{
  private static Camera camera1, camera2;
  private static Light light1, light2, light3;
  private static Sensor sensor;
  private static Alarm alarm;

  static SecurityFacade()
  {
    camera1 = new Camera();
    camera2 = new Camera();
    light1 = new Light();
    light2 = new Light();
    light3 = new Light();
    sensor = new Sensor();
    alarm = new Alarm();
  }
  
  public void Activate()
  {
    camera1.TurnOn();
    camera2.TurnOn();
    light1.TurnOn();
    light2.TurnOn();
    light3.TurnOn();
    sensor.Activate();
    alarm.Activate();
  }

  public void Deactivate()
  {
    camera1.TurnOff();
    camera2.TurnOff();
    light1.TurnOff();
    light2.TurnOff();
    light3.TurnOff();
    sensor.Deactivate();
    alarm.Deactivate();
  }
}
//////////////////////////////////////////////////////////////////////////////////
/* 客戶端 */
public class Client
{
  private static SecurityFacade security;

  public static void Main( string[] args )
  {
    security = new SecurityFacade();
    security.Activate();
    Console.WriteLine("\n--------------------\n");
    security.Deactivate();
  }
}

享元模式

在這裏插入圖片描述

享元模式 1:

package Flyweight;  
/////////////////////////////////////////////////////////////////////////
// 抽象享元角色 
public abstract class Flyweight{  
 public abstract void operation();  
}  
////////////////////////////////////////////////////////////////////////////
// 具體享元類 
public class ConcreteFlyweight extends Flyweight{  
 private String string;  
 public ConcreteFlyweight(String str){  
  string = str;  
 }  
 public void operation()  
 {  
  System.out.println("Concrete---Flyweight : " + string);  
 }  
} 
///////////////////////////////////////////////////////////////////////////////
// 享元工廠角色 
public class FlyweightFactory{  
  /////////////////////////////////////////////////////
  // hash 表,實現核心,每次通過工廠產生新實例都會保存在這裏
  // 創建新實例之前會在這裏查找
 private Hashtable flyweights = new Hashtable();//----------------------------1  
 public FlyweightFactory(){}  

 public Flyweight getFlyWeight(Object obj){  
  Flyweight flyweight = (Flyweight) flyweights.get(obj);//----------------2  
  if(flyweight == null){//---------------------------------------------------3  
   //產生新的ConcreteFlyweight  
   flyweight = new ConcreteFlyweight((String)obj);  
   flyweights.put(obj, flyweight);//--------------------------------------5  
  }  
  return flyweight;//---------------------------------------------------------6  
 }  

 public int getFlyweightSize(){  
  return flyweights.size();  
 }  
} 
/////////////////////////////////////////////////////////////////////////////////
// 調用
public class FlyweightPattern{  
 FlyweightFactory factory = new FlyweightFactory();   
 Flyweight fly1;  
 Flyweight fly2;  
 Flyweight fly3;  
 Flyweight fly4;  
 Flyweight fly5;  
 Flyweight fly6;  
 /** *//** Creates a new instance of FlyweightPattern */  
 public FlyweightPattern(){  
  fly1 = factory.getFlyWeight("Google");  
  fly2 = factory.getFlyWeight("Qutr");  
  fly3 = factory.getFlyWeight("Google");  
  fly4 = factory.getFlyWeight("Google");  
  fly5 = factory.getFlyWeight("Google");  
  fly6 = factory.getFlyWeight("Google");  
 }  
 public void showFlyweight(){  
  fly1.operation();  
  fly2.operation();  
  fly3.operation();  
  fly4.operation();  
  fly5.operation();  
  fly6.operation();  
  int objSize = factory.getFlyweightSize();  
  System.out.println("objSize = " + objSize);  
 }  
 public static void main(String[] args){  
  System.out.println("The FlyWeight Pattern!");  
  FlyweightPattern fp = new FlyweightPattern();  
  fp.showFlyweight();  
 }  
}  


/* 
    Concrete---Flyweight : Google  
    Concrete---Flyweight : Qutr  
    Concrete---Flyweight : Google  
    Concrete---Flyweight : Google  
    Concrete---Flyweight : Google  
    Concrete---Flyweight : Google  
    objSize = 2  
*/

單純享元:

/////////////////////////////////////////////////////////////////////////////////////////////////
// 抽象享元(Flyweight)角色
public interface Flyweight {
    //一個示意性方法,參數state是外蘊狀態
    public void operation(String state);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// 具體享元(ConcreteFlyweight)角色
public class ConcreteFlyweight implements Flyweight {
    private Character intrinsicState = null;
    /**
     * 構造函數,內蘊狀態作爲參數傳入
     * @param state
     */
    public ConcreteFlyweight(Character state){
        this.intrinsicState = state;
    }
    
    
    /**
     * 外蘊狀態作爲參數傳入方法中,改變方法的行爲,
     * 但是並不改變對象的內蘊狀態。
     */
    @Override
    public void operation(String state) {
        // TODO Auto-generated method stub
        System.out.println("Intrinsic State = " + this.intrinsicState);
        System.out.println("Extrinsic State = " + state);
    }

}
/////////////////////////////////////////////////////////////////////////////////////////////////
// 享元工廠(FlyweightFactory)角色
public class FlyweightFactory {
    /////////////////////////////////////////////////////////////////////////////
    // 通過這個 Hash 來保證複用的, 每次創建會在這裏查找
    private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>();
    
    public Flyweight factory(Character state){
        //先從緩存中查找對象
        Flyweight fly = files.get(state);
        if(fly == null){
            //如果對象不存在則創建一個新的Flyweight對象
            fly = new ConcreteFlyweight(state);
            //把這個新的Flyweight對象添加到緩存中
            files.put(state, fly);
        }
        return fly;
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// 客戶端角色
public class Client {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight fly = factory.factory(new Character('a'));
        fly.operation("First Call");
        
        fly = factory.factory(new Character('b'));
        fly.operation("Second Call");
        
        fly = factory.factory(new Character('a'));
        fly.operation("Third Call");
    }

}

複合享元:

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 抽象享元角色類
public interface Flyweight {
    //一個示意性方法,參數state是外蘊狀態
    public void operation(String state);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// 具體享元角色類
public class ConcreteFlyweight implements Flyweight {
    ////////////////////////////////////////////
    private Character intrinsicState = null;
    /**
     * 構造函數,內蘊狀態作爲參數傳入
     * @param state
     */
    public ConcreteFlyweight(Character state){
        this.intrinsicState = state;
    }
    
    
    /**
     * 外蘊狀態作爲參數傳入方法中,改變方法的行爲,
     * 但是並不改變對象的內蘊狀態。
     */
    @Override
    public void operation(String state) {
        // TODO Auto-generated method stub
        System.out.println("Intrinsic State = " + this.intrinsicState);
        System.out.println("Extrinsic State = " + state);
    }

}

/* 具體複合享元角色
        複合享元對象是由單純享元對象通過複合而成的,因此它提供了add()這樣的聚集管理方法。由於一個複合享元對象具有不同的聚集
    元素,這些聚集元素在複合享元對象被創建之後加入,這本身就意味着複合享元對象的狀態是會改變的,因此複合享元對象是不能共享的。
      複合享元角色實現了抽象享元角色所規定的接口,也就是operation()方法,這個方法有一個參數,代表複合享元對象的外蘊狀態。一個
    複合享元對象的所有單純享元對象元素的外蘊狀態都是與複合享元對象的外蘊狀態相等的;而一個複合享元對象所含有的單純享元對象的內蘊狀態
    一般是不相等的,不然就沒有使用價值了。*/
public class ConcreteCompositeFlyweight implements Flyweight {
    
    ///////////////////////////////////////////////////////////////
    // 保存複合享元數據,即多個數據
    private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>();
    /**
     * 增加一個新的單純享元對象到聚集中
     */
    public void add(Character key , Flyweight fly){
        files.put(key,fly);
    }
    /**
     * 外蘊狀態作爲參數傳入到方法中
     */
    @Override
    public void operation(String state) {
        Flyweight fly = null;
        for(Object o : files.keySet()){
            fly = files.get(o);
            fly.operation(state);
        }
        
    }

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 享元工廠角色提供兩種不同的方法,一種用於提供單純享元對象,另一種用於提供複合享元對象。
public class FlyweightFactory {
    private Map<Character,Flyweight> files = new HashMap<Character,Flyweight>();
    /**
     * 複合享元工廠方法
     */
    public Flyweight factory(List<Character> compositeState){
        ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
        
        for(Character state : compositeState){
            compositeFly.add(state,this.factory(state));
        }
        
        return compositeFly;
    }
    /**
     * 單純享元工廠方法
     */
    public Flyweight factory(Character state){
        //先從緩存中查找對象
        Flyweight fly = files.get(state);
        if(fly == null){
            //如果對象不存在則創建一個新的Flyweight對象
            fly = new ConcreteFlyweight(state);
            //把這個新的Flyweight對象添加到緩存中
            files.put(state, fly);
        }
        return fly;
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
// 客戶端角色
public class Client {

    public static void main(String[] args) {
        // 創建一個數組 
        List<Character> compositeState = new ArrayList<Character>();
        compositeState.add('a');
        compositeState.add('b');
        compositeState.add('c');
        compositeState.add('a');
        compositeState.add('b');
        // 複合享元測試
        FlyweightFactory flyFactory = new FlyweightFactory();
        Flyweight compositeFly1 = flyFactory.factory(compositeState);
        Flyweight compositeFly2 = flyFactory.factory(compositeState);
        compositeFly1.operation("Composite Call");
        
        System.out.println("---------------------------------");        
        System.out.println("複合享元模式是否可以共享對象:" + (compositeFly1 == compositeFly2));
        // 單純享元測試
        Character state = 'a';
        Flyweight fly1 = flyFactory.factory(state);
        Flyweight fly2 = flyFactory.factory(state);
        System.out.println("單純享元模式是否可以共享對象:" + (fly1 == fly2));
    }
}

裝飾器模式

在這裏插入圖片描述

裝飾器模式1:

///////////////////////////////////////////////////////////////////////////////////////////
//定義抽象被裝飾者: Component 
public interface Human {  
    public void wearClothes();  
  
    public void walkToWhere();  
}  
//////////////////////////////////////////////////////////////////////////////////////////////
//定義具體被裝飾者: ConcreteComponent 被裝飾者初始狀態有些自己的裝飾  
public class Person implements Human {  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        System.out.println("穿什麼呢。。");  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        System.out.println("去哪裏呢。。");  
    }  
}  
/////////////////////////////////////////////////////////////////////////////////////////////
//定義抽象裝飾者: Decorator   
public abstract class Decorator implements Human {  
    private Human human;  
  
    public Decorator(Human human) {  
        this.human = human;  
    }  
  
    public void wearClothes() {  
        human.wearClothes();  
    }  
  
    public void walkToWhere() {  
        human.walkToWhere();  
    }  
}  
////////////////////////////////////////////////////////////////////////////////////////////  
//下面定義三種具體裝飾: ConcreteDecorator 這是第一個,第二個第三個功能依次細化,即裝飾者的功能越來越多  
public class Decorator_zero extends Decorator {  
  
    public Decorator_zero(Human human) {  
        super(human);  
    }  
  
    public void goHome() {  
        System.out.println("進房子。。");  
    }  
  
    public void findMap() {  
        System.out.println("書房找找Map。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        goHome();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findMap();  
    }  
}  
// 具體裝飾:  Decorator_first
public class Decorator_first extends Decorator {  
  
    public Decorator_first(Human human) {  
        super(human);  
    }  
  
    public void goClothespress() {  
        System.out.println("去衣櫃找找看。。");  
    }  
  
    public void findPlaceOnMap() {  
        System.out.println("在Map上找找。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        goClothespress();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findPlaceOnMap();  
    }  
}  
// 具體裝飾:  Decorator_two  
public class Decorator_two extends Decorator {  
  
    public Decorator_two(Human human) {  
        super(human);  
    }  
  
    public void findClothes() {  
        System.out.println("找到一件D&G。。");  
    }  
  
    public void findTheTarget() {  
        System.out.println("在Map上找到神祕花園和城堡。。");  
    }  
  
    @Override  
    public void wearClothes() {  
        // TODO Auto-generated method stub  
        super.wearClothes();  
        findClothes();  
    }  
  
    @Override  
    public void walkToWhere() {  
        // TODO Auto-generated method stub  
        super.walkToWhere();  
        findTheTarget();  
    }  
}  
  
///////////////////////////////////////////////////////////////////////////////////////////
//測試類
public class Test {  
    public static void main(String[] args) {  
        // 聲明一個被裝飾者 
        Human person = new Person();  

        // 聲明一個裝飾:通過具體的裝飾來打扮被裝飾者,這裏是一個 Decorator_two 對象 
        Decorator decorator = new Decorator_two(new Decorator_first(new Decorator_zero(person)));

        // 基類指針指向 Decorator_two(), 調用流程爲:Decorator_two.wearClothes() -->  Decorator_first.wearClothes() --> Decorator_zero.wearClothes() 
        decorator.wearClothes();  
        decorator.walkToWhere();  
    }  
}  

裝飾器模式 2:

/* 現在需要一個漢堡,主體是雞腿堡,可以選擇添加生菜、醬、辣椒等等許多其他的配料,這種情況下就可以使用裝飾者模式。*/

package decorator;   
///////////////////////////////////////////////////////////////////////////////////////////// 
// 漢堡基類(被裝飾者,相當於上面的(Component 抽象構件角色)    
public abstract class Humburger {    
        
    protected  String name ;    
        
    public String getName(){    
        return name;    
    }    
        
    public abstract double getPrice();    
    
}    
//////////////////////////////////////////////////////////////////////////////////////////////
// 雞腿堡類(被裝飾者的初始狀態,有些自己的簡單裝飾,相當於上面的(ConcreteComponent 具體構件角色)
public class ChickenBurger extends Humburger {    
        
    public ChickenBurger(){    
        name = "雞腿堡";    
    }    
    
    @Override    
    public double getPrice() {    
        return 10;    
    }    
    
}    
//////////////////////////////////////////////////////////////////////////////////////////////////////
// 配料的基類(裝飾者,用來對漢堡進行多層裝飾,每層裝飾增加一些配料,相當於上面(Decorator 裝飾角色)
public abstract class Condiment extends Humburger {    
        
    public abstract String getName();    
    
}    
//////////////////////////////////////////////////////////////////////////////////////////////
// 生菜(裝飾者的第一層,相當於上面的(ConcreteDecoratorA 具體裝飾角色A)
public class Lettuce extends Condiment {    
        
    Humburger humburger;    
        
    public Lettuce(Humburger humburger){    
        this.humburger = humburger;    
    }    
    
    @Override    
    public String getName() {    
        return humburger.getName()+" 加生菜";    
    }    
    
    @Override    
    public double getPrice() {    
        return humburger.getPrice()+1.5;    
    }    
    
}    

// 辣椒(裝飾者的第二層,相當於上面的(ConcreteDecoratorB 具體裝飾角色B)
public class Chilli extends Condiment {    
        
    Humburger humburger;    
        
    public Chilli(Humburger humburger){    
        this.humburger = humburger;    
            
    }    
    
    @Override    
    public String getName() {    
        return humburger.getName()+" 加辣椒";    
    }    
    
    @Override    
    public double getPrice() {    
        return humburger.getPrice();  //辣椒是免費的哦    
    }    
    
}    
/////////////////////////////////////////////////////////////////////////////////////////////
// 測試類
public class Test {    
    
    public static void main(String[] args) {    
        // 獲得一個被裝飾類:雞腿堡
        Humburger humburger = new ChickenBurger();    
        System.out.println(humburger.getName()+"  價錢:"+humburger.getPrice());    

        // 通過【雞腿堡】初始化生菜
        Lettuce lettuce = new Lettuce(humburger);    
        System.out.println(lettuce.getName()+"  價錢:"+lettuce.getPrice());   

        // 通過【雞腿堡】初始化辣椒 
        Chilli chilli = new Chilli(humburger);    
        System.out.println(chilli.getName()+"  價錢:"+chilli.getPrice());    

        // 通過【雞腿堡+生菜】初始化辣椒
        Chilli chilli2 = new Chilli(lettuce);    
        System.out.println(chilli2.getName()+"  價錢:"+chilli2.getPrice());    
    }    
    
}    



/* 
輸出:
    雞腿堡  價錢:10.0    
    雞腿堡 加生菜  價錢:11.5    
    雞腿堡 加辣椒  價錢:10.0    
    雞腿堡 加生菜 加辣椒  價錢:11.5    
*/

組合模式

在這裏插入圖片描述

組合模式 1:

//////////////////////////////////////////////////////////////////////////
/// 店面類 抽象出來的店面部件
// component 組件
public abstract class Storefront
{
    //店名
    protected string storeName = string.Empty;
    public string StoreName
    {
        get
        {
            return storeName;
        }
    }

    //添加店面
    public abstract void Add(Storefront store);
    //刪除店面
    public abstract void Remove(Storefront store);

    //定義所有部件公用的行爲 刷卡行爲
    public abstract void PayByCard();
}
///////////////////////////////////////////////////////////////////////////////////
// composite 組件:直營店
public class StoreOrBranch : Storefront
{
    // 鏈表,用來保存 composite 組件 或 leaf 組件
    List<Storefront> myStoreList = new List<Storefront>();
    //構造函數
    public StoreOrBranch() { }
    public StoreOrBranch(string storeName)
    {
        this.storeName = storeName;
    }
    
    //刷卡消費
    public override void PayByCard()
    {
        Console.WriteLine("店面{0}的積分已累加進該會員卡", storeName);
        foreach (Storefront sf in myStoreList)
        {
            sf.PayByCard();
        }
    }

    //增加店面
    public override void Add(Storefront store)
    {
        myStoreList.Add(store);
    }

    //解除店面
    public override void Remove(Storefront store)
    {
        myStoreList.Remove(store);
    }
}
///////////////////////////////////////////////////////////////////////////////////////
// leaf 組件:加盟店
public class JoinInStore : Storefront
{
    //構造函數
    public JoinInStore() { }
    public JoinInStore(string storeName)
    {
        this.storeName = storeName;
    }
    //刷卡消費
    public override void PayByCard()
    {
        Console.WriteLine("店面{0}的積分已累加進該會員卡", storeName);
    }

    public override void Add(Storefront store)
    {
        throw new NotImplementedException();
    }

    public override void Remove(Storefront store)
    {
        throw new NotImplementedException();
    }
}
/////////////////////////////////////////////////////////////////////////////////
static void Main(string[] args)
{
        // 直營店有自己的鏈表,可以保存下面的加盟店或直營店
        StoreOrBranch store = new StoreOrBranch("朝陽總店");
        StoreOrBranch brach = new StoreOrBranch("東城分店");
        
        JoinInStore jstore = new JoinInStore("海淀加盟店一");
        JoinInStore jstore1 = new JoinInStore("上地加盟店二");

        /* 樹形結構:
                朝陽總店
                東城分店
        海淀加盟店一 上地加盟店二 
        */
        brach.Add(jstore);
        brach.Add(jstore1);
        store.Add(brach);

        store.PayByCard();
}

組合模式 2:

package design.composite;  

//////////////////////////////////////////////////////////////////////////////////////////
// component 抽象構件角色
public abstract class Company {  
    private String name;  
  
    public Company(String name) {  
        this.name = name;  
    }  
  
    public Company() {  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    protected abstract void add(Company company);  
  
    protected abstract void romove(Company company);  
  
    protected abstract void display(int depth);  
}  
////////////////////////////////////////////////////////////////////////////////////////////////
// composite 組件 1  
public class ConcreteCompany extends Company {  
    private List<Company> cList;  
  
    public ConcreteCompany() {  
        cList = new ArrayList<Company>();  
    }  
  
    public ConcreteCompany(String name) {  
        super(name);   
        cList = new ArrayList<Company>() ;   
    }  
  
    @Override  
    protected void add(Company company) {  
        cList.add(company);  
    }  
  
    @Override  
    protected void display(int depth) {  
        // TODO Auto-generated method stub  
        StringBuilder sb = new StringBuilder("");  
        for (int i = 0; i < depth; i++) {  
            sb.append("-");   
        }  
        System.out.println(new String(sb) + this.getName());  
        for (Company c : cList) {  
            c.display(depth + 2);  
        }  
    }  
  
    @Override  
    protected void romove(Company company) {  
        cList.remove(company);  
    }  
}  
///////////////////////////////////////////////////////////////////////////////////////////
// leaf 組件 1 
public class FinanceDepartment extends Company {  
      
      
    public FinanceDepartment(){  
          
    }  
      
    public FinanceDepartment(String name){  
        super(name);  
    }  
      
    @Override  
    protected void add(Company company) {  
  
    }  
  
    @Override  
    protected void display(int depth) {  
        StringBuilder sb = new StringBuilder("");  
        for (int i = 0; i < depth; i++) {  
            sb.append("-");  
        }  
        System.out.println(new String(sb) + this.getName() ) ;   
    }  
  
    @Override  
    protected void romove(Company company) {  
          
    }  
      
}  
// leaf 組件 2 
public class HRDepartment extends Company {  
      
      
    public HRDepartment(){  
          
    }  
      
    public HRDepartment(String name){  
        super(name);  
    }  
      
    @Override  
    protected void add(Company company) {  
  
    }  
  
    @Override  
    protected void display(int depth) {  
        StringBuilder sb = new StringBuilder("");  
        for (int i = 0; i < depth; i++) {  
            sb.append("-");   
        }  
        System.out.println(new String(sb) + this.getName() ) ;   
    }  
  
    @Override  
    protected void romove(Company company) {  
          
    }  
      
}  
  
////////////////////////////////////////////////////////////////////////////////////////////////  
package design.composite;  
 
/* 測試,最終形成了一種樹形結構 
            總公司
            /  |  \ 

        各個  ... 分公司
*/ 
public class Client {  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        Company root = new ConcreteCompany();  
        root.setName("北京總公司");  
        root.add(new HRDepartment("總公司人力資源部"));  
        root.add(new FinanceDepartment("總公司財務部"));  

        Company shandongCom = new ConcreteCompany("山東分公司");  
        shandongCom.add(new HRDepartment("山東分公司人力資源部"));  
        shandongCom.add(new FinanceDepartment("山東分公司賬務部"));  

        Company zaozhuangCom = new ConcreteCompany("棗莊辦事處");  
        zaozhuangCom.add(new FinanceDepartment("棗莊辦事處財務部"));  
        zaozhuangCom.add(new HRDepartment("棗莊辦事處人力資源部"));  

        Company jinanCom = new ConcreteCompany("濟南辦事處");  
        jinanCom.add(new FinanceDepartment("濟南辦事處財務部"));  
        jinanCom.add(new HRDepartment("濟南辦事處人力資源部"));   


        shandongCom.add(jinanCom);  
        shandongCom.add(zaozhuangCom);  

        Company huadongCom = new ConcreteCompany("上海華東分公司");  
        huadongCom.add(new HRDepartment("上海華東分公司人力資源部"));  
        huadongCom.add(new FinanceDepartment("上海華東分公司賬務部"));  

        Company hangzhouCom = new ConcreteCompany("杭州辦事處");  
        hangzhouCom.add(new FinanceDepartment("杭州辦事處財務部"));  
        hangzhouCom.add(new HRDepartment("杭州辦事處人力資源部"));  

        Company nanjingCom = new ConcreteCompany("南京辦事處");  
        nanjingCom.add(new FinanceDepartment("南京辦事處財務部"));  
        nanjingCom.add(new HRDepartment("南京辦事處人力資源部"));  

        huadongCom.add(hangzhouCom);  
        huadongCom.add(nanjingCom);   

        root.add(shandongCom);  
        root.add(huadongCom);  
        root.display(0);  
    }  
  
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章