12種設計模式C++源代碼

目錄

//1.簡單工廠

//2.工廠方法

//3.抽象工廠

//4.策略模式

//5.裝飾模式

//6.模板方法

//7.門面模式

//8.適配器模式

//9.觀察者模式

//10.建造者模式

//11.組合模式

//12.單例模式

//13. 狀態模式

//14.反射機制


 


//1.簡單工廠

class Product {
public:
    virtual void function() = 0;
    Product() {

    }
    virtual ~Product()
    {

    }
};

class ProductA :public Product {
public:
    void function() {
        cout<<"ProductA"<<endl;
    }
};

class ProductB :public Product {
public:
    void function() {
        cout << "ProductB" << endl;
    }
};

class SimpleFactory {
public:
    static Product* CreateProduct(string name) {
        if (name == "A")
            return new ProductA();
        else if (name == "B")
            return new ProductB();
    }
};

int main() {
    Product* p;
    p = SimpleFactory::CreateProduct("A");
    p->function();
    return 0;
}


 

//2.工廠方法


 

class Product {
public:
    virtual void Disp() = 0;
};

class ConcreteProductA :public Product {
public:
    void Disp() {
        cout<<"ProductA"<<endl;
    }
};

class ConcreteProductB :public Product {
public:
    void Disp() {
        cout << "ProductB" << endl;
    }
};

class IFactory {
public:
    virtual Product* CreateProduct() = 0;
};

class FactoryA :public IFactory {
public:
    static Product* CreateProduct() {
        return new ConcreteProductA();
    }
};

class FactoryB :public IFactory {
public:
    static Product* CreateProduct() {
        return new ConcreteProductB();
    }
};

int main() {
    Product* product = FactoryA::CreateProduct();
    product->Disp();
    return 0;
}

 

//3.抽象工廠


 

class ProductA {
public:
    virtual void Disp() = 0;
};

class ProductA1:public ProductA{
public:
    void Disp() {
        cout<<"ProductA: ProductA1"<<endl;
    }
};

class ProductA2 :public ProductA {
public:
    void Disp() {
        cout << "ProductA: ProductA2" << endl;
    }
};
class ProductB {
public:
    virtual void Disp() = 0;
};

class ProductB1 :public ProductB {
public:
    void Disp() {
        cout << "ProductB: ProductB1" << endl;
    }
};

class ProductB2 :public ProductB {
public:
    void Disp() {
        cout << "ProductB: ProductB2" << endl;
    }
};

class IFactory {
public:
    virtual ProductA* CreateProductA() = 0;
    virtual ProductB* CreateProductB() = 0;
};

class Factory1 :public IFactory {
public:
    static ProductA* CreateProductA() {
        return new ProductA1();
    }
    static ProductB* CreateProductB() {
        return new ProductB1();
    }
};

class Factory2 :public IFactory {
public:
    static ProductA* CreateProductA() {
        return new ProductA2();
    }
    static ProductB* CreateProductB() {
        return new ProductB2();
    }
};

class Access {
private:
    static string str;
public:
    static ProductA* createProductA() {
        if (str == "1")
            return new ProductA1();
        else if (str == "2")
            return new ProductA2();
    }
    static ProductB* createProductB() {
        if (str == "1")
            return new ProductB1();
        else if (str == "2")
            return new ProductB2();
    }
};
string Access::str = "2";

int main() {
    //1.--------------
    //Factory2* f1;
    //ProductA* A;
    //ProductB* B;
    //A = f1->CreateProductA();
    //B = f1->CreateProductB();
    //A->Disp();
    //B->Disp();
    //2.--------------
    ProductA* A = Access::createProductA();
    ProductB* B = Access::createProductB();
    A->Disp();
    B->Disp();
    return 0;
}


 

//4.策略模式


 

class IStrategy {
public:
    virtual void Disp() = 0;
};

class StrategyA :public IStrategy {
public:
    void Disp() {
        cout<<"StrategyA"<<endl;
    }
};
class StrategyB :public IStrategy {
public:
    void Disp() {
        cout << "StrategyB" << endl;
    }
};
class StrategyC :public IStrategy {
public:
    void Disp() {
        cout << "StrategyC" << endl;
    }
};

class Context {
private:
    IStrategy* startegy;
public:
    Context(IStrategy* strategy) {
        this->startegy = strategy;
    }
    void Interface() {
        startegy->Disp();
    }
};

int main() {

    Context* context = new Context(new StrategyB());
    context->Interface();
    return 0;
}


 

//5.裝飾模式


 

class Component {
public:
    virtual void Operation() = 0;
};

class ConcreteComponent : public Component {
public:
    void Operation() {
        cout<<"ConcreteComponent"<<endl;
    }
};

class Decorator : public Component {
protected:
    Component* component;
public:
    Decorator(Component* component) {
        this->component = component;
    }
    void Operation() {
        component->Operation();
    }
};

class ConcreteDecoratorA :public Decorator {
public:
    ConcreteDecoratorA(Component* com):Decorator(com) {
        component = com;
    }
    void Operation() {
        component->Operation();
    }
};

class ConcreteDecoratorB :public Decorator {
public:

    ConcreteDecoratorB(Component* com) :Decorator(com) {
        component = com;
    }

    void Operation() {
        component->Operation();
        AddBehaviour();
    }

    void AddBehaviour() {
        cout<<"Extra Operation"<<endl;
    }
};

int main() {
    Component* componmet;
    Component* concrete_p = new ConcreteComponent();
    componmet = new ConcreteDecoratorB(concrete_p);
    componmet->Operation();

    return 0;
}


 

//6.模板方法


 

class AbstractClass {
public:
    void TemplateMethod() {
        cout<<"TemplateMethod"<<endl;
        function1();
        function2();
    }
    virtual void function1() = 0;
    virtual void function2() = 0;
};

class SubClass :public AbstractClass {
public:
    void function1() {
        cout << "function1" << endl;
    }
    void function2() {
        cout << "function2" << endl;
    }
};

int main() {
    AbstractClass* c = new SubClass();
    c->TemplateMethod();
    return 0;
}


 

//7.門面模式


 

class SubSystemA {
public:
    void MethodA() {
        cout<<"A"<<endl;
    }
};

class SubSystemB {
public:
    void MethodB() {
        cout << "B" << endl;
    }
};

class SubSystemC {
public:
    void MethodC() {
        cout << "C" << endl;
    }
};

class Facade {
private:
    SubSystemA* A;
    SubSystemB* B;
    SubSystemC* C;
public:
    Facade() {
        A = new SubSystemA();
        B = new SubSystemB();
        C = new SubSystemC();
    }
    void Method() {
        A->MethodA();
        B->MethodB();
        C->MethodC();
    }
};

int main() {
    Facade* f = new Facade();
    f->Method();
    return 0;
}


 

//8.適配器模式



 

//////////////////類適配器模式+對象適配器模式
class Target {
public:
    virtual void request() {
        cout << "Request" << endl;
    };
};

class Adaptee {
public:
    void SpecificRequest() {
        cout<<"SpecificRequest"<<endl;
    }
};

class ClassAdapter :public Adaptee,public Target {
public:
    virtual void request() {
        SpecificRequest();
    }
};

class ObjectAdapter :public Target{
private:
    Adaptee* adaptee;
public:
    ObjectAdapter(Adaptee* obj) :adaptee(obj) {
    }
    void request() {
        adaptee->SpecificRequest();
    }
};

int main() {
    //類適配器模式
    //Target* target = new ClassAdapter();
    //target->request();

    //對象適配器模式
    Adaptee* adaptee = new Adaptee();
    Target* target = new ObjectAdapter(adaptee);
    target->request();
    return 0;
}

 

//9.觀察者模式


 

class Observer {
public:
    virtual void response(int) = 0;
};

class Subject {
public:
    virtual void Add(Observer*) = 0;
    virtual void Remove(Observer*) = 0;
    virtual void Notify() = 0;
};

class ConcreteObserver1 :public Observer {
private:
    Subject* subject;
public:
    ConcreteObserver1(Subject* subject) :subject(subject) {

    }
    void response(int state) {
        cout<< "Observer1" << state<<endl;
    }
};

class ConcreteObserver2 :public Observer {
private:
    Subject* subject;
public:
    ConcreteObserver2(Subject* subject) :subject(subject) {

    }
    void response(int state) {
        cout <<"Observer2"<< state << endl;
    }
};
class ConcreteSubject :public Subject {
protected:
    list<Observer*> observers;
    int state;
public:
    void SetState(int state) {
        this->state = state;
    }
    void Add(Observer* observer) {
        observers.push_back(observer);
    }
    void Remove(Observer* observer) {
        observers.remove(observer);
    }
    void Notify() {
        list<Observer*>::iterator it = observers.begin();
        while (it != observers.end()) {
            (*it)->response(state);
            ++it;
        }
    }
};

int main() {
    ConcreteSubject* subject = new ConcreteSubject();

    Observer* observer1 =new ConcreteObserver1(subject);
    Observer* observer2 = new ConcreteObserver2(subject);

    subject->SetState(1);

    subject->Add(observer1);
    subject->Add(observer2);

    subject->Remove(observer1);
    subject->Notify();
    return 0;
}


 

//10.建造者模式


 

class Product {
public:
    virtual void ADD(string) = 0;
    virtual void Show() = 0;
};

class ConcreteProduct :public Product {
private:
    list<string> parts;
public:
    void ADD(string part) {
        parts.push_back(part);
    }
    void Show() {
        list<string>::iterator it = parts.begin();
        while (it != parts.end()) {
            cout << (*it) << endl;
            it++;
        }
    }
};

class Builder {
public:
    virtual void BuildPartA() = 0;
    virtual void BuildPartB() = 0;
    virtual void BuildPartC() = 0;
    virtual ConcreteProduct *GetResult() = 0;
};

class ConcreteBuilder :public Builder {
private:
    ConcreteProduct* product = new ConcreteProduct();
public:
    void BuildPartA() {
        product->ADD("A");
    }
    void BuildPartB() {
        product->ADD("B");
    }
    void BuildPartC() {
        product->ADD("C");
    }
    ConcreteProduct *GetResult() {
        return product;
    }
};

class Director {
private:
    Builder* builder;
public:
    Director(Builder* builder) {
        this->builder = builder;
    }
    void CreateProduct() {
        builder->BuildPartB();
        builder->BuildPartA();
        builder->BuildPartC();
    }
};

int main() {
    Builder* builder = new ConcreteBuilder();
    Director* director = new Director(builder);
    director->CreateProduct();

    Product* product = new ConcreteProduct();
    product = builder->GetResult();
    product->Show();
    return 0;
}


 

//11.組合模式



//透明式組合模式
 

class Component {
protected:
    string name;
public:
    Component(string _name) {
        name = _name;
    }
    virtual void add(Component* c) = 0;
    virtual void remove(Component* c) = 0;
    virtual void Operation(int depth) = 0;
};

class Leaf :public Component {

public:
    Leaf(string _name):Component(_name) {
        name = _name;
    }
    void add(Component* c) {

    }
    void remove(Component* c) {

    }
    void Operation(int depth) {
        string temp = "---------------------";
        cout << "-" << temp.substr(0, depth) << "  " << name << endl;
    }
};

class Compisite :public Component {
private:
    list<Component*> children;
public:
    Compisite(string _name) :Component(_name) {
        this->name = _name;
    }
    void add(Component* child) {
        children.push_back(child);
    }
    void remove(Component* child) {
        children.remove(child);
    }
    void Operation(int depth) {
        string temp = "---------------------";
        cout << "-" << temp.substr(0, depth) << "  " << name << endl;
        list<Component *>::iterator it = children.begin();
        while (it != children.end())
        {
            (*it)->Operation(depth + 2);
            it++;
        }
    }
};

int main() {
    Component* c0 = new Compisite("c0");
    Component* c1 = new Compisite("c1");

    Component* l1 = new Leaf("1");
    Component* l2 = new Leaf("2");
    Component* l3 = new Leaf("3");

    c0->add(l1);
    c0->add(c1);
    c1->add(l2);
    c1->add(l3);

    c0->Operation(2);
    return 0;
}



//安全式組合模式
 

class Component {
protected:
    string name;
public:
    Component(string _name) {
        name = _name;
    }
    virtual void Operation(int depth) = 0;
};

class Leaf :public Component {
public:
    Leaf(string _name):Component(_name) {
        name = _name;
    }
    void Operation(int depth) {
        string temp = "---------------------";
        cout << "-" << temp.substr(0, depth) << "  " << name << endl;
    }
};

class Compisite :public Component {
private:
    list<Component*> children;
public:
    Compisite(string _name) :Component(_name) {
        this->name = _name;
    }
    void add(Component* child) {
        children.push_back(child);
    }
    void remove(Component* child) {
        children.remove(child);
    }
    void Operation(int depth) {
        string temp = "---------------------";
        cout << "-" << temp.substr(0, depth) << "  " << name << endl;
        list<Component *>::iterator it = children.begin();
        while (it != children.end())
        {
            (*it)->Operation(depth + 1);
            it++;
        }
    }
};

int main() {
    Compisite* c0 = new Compisite("c0");
    Compisite* c1 = new Compisite("c1");

    Leaf* l1 = new Leaf("1");
    Leaf* l2 = new Leaf("2");
    Leaf* l3 = new Leaf("3");

    c0->add(l1);
    c0->add(c1);
    c1->add(l2);
    c1->add(l3);

    c0->Operation(0);
    return 0;
}


 

//12.單例模式


//懶漢單例模式
 

class Singleton {
private:
    static Singleton* instance;
    Singleton() {

    }
public:
    static Singleton* GetInstance() {
        if (instance == NULL)
            instance = new Singleton();
        return instance;
    }
};
Singleton *Singleton::instance = NULL;

int main() {
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();
    if (s1 == s2)
        cout<<"實例相同"<<endl;
    return 0;
}


//餓漢單例模式
 

class Singleton {
private:
    static Singleton* instance;
public:
    static Singleton* GetInstance() {
        return instance;
    }
};

Singleton *Singleton::instance = new Singleton();

int main() {
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();
    if (s1 == s2)
        cout<<"實例相同"<<endl;
    return 0;
}


//懶漢單例模式--雙鎖機制
 

class Singleton {
private:
    static Singleton* instance;
    Singleton() {

    }
public:
    static Singleton* GetInstance() {

        if (instance == NULL) {
            mt.lock();
            if (instance == NULL) {
                    instance = new Singleton();
                    mt.unlock();
                    return instance;
            }
        }
        mt.unlock();
        return instance;
    }
};

Singleton *Singleton::instance = NULL;

int main() {
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();
    if (s1 == s2)
        cout<<"實例相同"<<endl;
    return 0;
}

 

//懶漢式單例(magic static )——局部靜態變量

 

class Singleton {
private:
    Singleton() {
        cout << "constructor called!" << endl;
    }
public:
    Singleton(const Singleton*) = delete;
    Singleton *operator=(const Singleton*) = delete;
    static Singleton *GetInstance() {
        static Singleton *instance;
        return instance;
    }
    ~Singleton() {
        cout << "destructor called!" << endl;
    }
};

//爲什麼沒有“線程安全的餓漢實現”,因爲餓漢實現本來就是線程安全的,不用加鎖。

//13. 狀態模式

 


class State {
public:
	virtual void Handle(Context* context) = 0;
};

class StateA : public State {
public:
	void Handle(Context* context) {
		cout<<"StateA"<<endl;
	}
};

class StateB : public State {
public:
	void Handle(Context* context) {
		cout << "StateB" << endl;
	}
};

class Context {
private:
	State* state;
public:
	Context(State* state) :state(state) {
	}
	void Request() {
		if (state)
			state->Handle(this);
	}
	void ChangeState(State* state) {
		this->state = state;
	}
};

int main() {
	State* stateA = new StateA();
	State* stateB = new StateB();
	Context* p = new Context(stateA);
	p->Request();
	p->ChangeState(stateB);
	p->Request();
	return 0;
}

//14.反射機制

class shape
{
public:
	shape() {}
	virtual ~shape() {}
	virtual void draw() = 0;
};
class A :public shape
{
public:
	A() {}
	~A() {}
	void draw()
	{
		cout << "this is a A" << endl;
	}
};
class B :public shape
{
public:
	B() {}
	~B() {}
	void draw()
	{
		cout << "this is a B" << endl;
	}
};
class C :public shape
{
public:
	C() {}
	~C() {}
	void draw()
	{
		cout << "this a C" << endl;
	}
};


class factory
{
public:
	factory() {
		m_map.insert(pair<string, PTRF>("A", &factory::createA));
		m_map.insert(pair<string, PTRF>("B", &factory::createB));
	}
	shape *create(string type)
	{
		map<string, PTRF>::iterator it = m_map.find(type);
		if (it != m_map.end())
		{
			return (this->*(it->second))();
		}
		else
		{
			return nullptr;
		}
	}
	~factory() {}
private:

	typedef shape* (factory:: *PTRF)();
	map<string, PTRF> m_map;
	shape *createA()
	{
		A *r = new A();
		return r;
	}
	shape * createB()
	{
		B *p = new B();
		return p;
	}
	shape *createtC()
	{
		C *t = new C();
		return t;
	}
};
int main()
{
	shape *s = nullptr;
	factory f;
	string a;
	cin >> a;
	s = f.create(a);
	if (s)
	{
		s->draw();
	}
	else
	{
		cout << "no this class" << endl;
	}
	return 0;
}

 

發佈了23 篇原創文章 · 獲贊 11 · 訪問量 6981
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章