1 , 简 单 工 厂 方 法 : \red{1,简单工厂方法:} 1,简单工厂方法:
通过switch case语句块判断需要返回实例化哪个类。
然后通过基类指针指向派生类,实现不同的实例。
优
点
:
\orange{优点:}
优点: 基本工厂方法,不需要关注实例化过程。
缺
点
:
\green{缺点:}
缺点: switch是最low的方法,臃肿,非常不推荐。
class Base{
public:
virtual void print() = 0;
};
class A : public Base{
public:
void print(){ puts("A");}
};
class B : public Base{
public:
void print(){ puts("B");}
};
class ABFactory{
public:
Base* createAorB(char type){
switch(type){
case 'A':
return new A();
case 'B':
return new B();
default:
return NULL;
}
}
};
int main(){
ABFactory* factory = new ABFactory();
Base* a = factory->createAorB('A');
Base* b = factory->createAorB('B');
a->print();
b->print();
return 0;
}
2 , 抽 象 工 厂 方 法 模 式 : \red{2,抽象工厂方法模式:} 2,抽象工厂方法模式:
有一个抽象工厂基类,在工厂基类上派生出不同的实例工厂。
优
点
:
\orange{ 优点:}
优点: 扩展性比较好
缺
点
:
\green{缺点:}
缺点: 每一个实例都要对应一个工厂,代码量大。
class Base{
public:
virtual void print() = 0;
};
class A : public Base{
public:
virtual void print(){ puts("A");}
};
class B : public Base{
public:
virtual void print(){ puts("B");}
};
class Factory{
public:
virtual Base* product() = 0;
};
class FactoryA: public Factory{
public:
virtual Base* product(){ return new A();}
};
class FactoryB: public Factory{
public:
virtual Base* product(){ return new B();}
};
int main(){
Factory* FA = new FactoryA();
Factory* FB = new FactoryB();
Base* A = FA->product();
Base* B = FB->product();
A->print();
B->print();
return 0;
}
3 , 单 例 模 式 : \red{3,单例模式:} 3,单例模式:
懒 汉 模 式 v s 饿 汉 模 式 : \orange{懒汉模式\ vs\ 饿汉模式:} 懒汉模式 vs 饿汉模式:
懒 汉 模 式 : \blue{懒汉模式:} 懒汉模式:
没有用到时,不会实例化
mutex mt;
class Singleton{
private:
static Singleton* s;
private:
Singleton(){} // 私有构造
Singleton(const Singleton& ) = delete; // 拷贝构造
Singleton& operator=(const Singleton& ) = delete; //赋值构造
public:
static Singleton* getInstance();
};
Singleton* Singleton::s = NULL;
Singleton* Singleton::getInstance(){
if(s == NULL){
mt.lock();
if(s == NULL) s = new Singleton();
mt.unlock();
}
return s;
}
饿 汉 模 式 : \blue{饿汉模式:} 饿汉模式:
初始化时即存在实例
class Singleton{
private:
static Singleton* s;
private:
Singleton(){}
Singleton(const Singleton& ) = delete;
Singleton& operator=(const Singleton& ) = delete;
public:
static Singleton* getInstance();
};
Singleton* Singleton::s = new Singleton();
Singleton* Singleton::getInstance(){ return s; }
4 , 装 饰 模 式 : \red{4,装饰模式:} 4,装饰模式:
在基础功能上添加新功能,用组合指针实现。
// 基础类
class Human{
public:
void walk(){ puts("walk"); }
};
// 在基础类上添加新功能
class Human_fly{
private:
Human* man;
void add_fly(){ puts("Install fly"); }
public:
Human_fly(Human* h):man(h){}
void walk(){
man->walk();
add_fly();
}
};
int main(){
Human* Aman = new Human();
Human_fly* Bman = new Human_fly(Aman);
Bman->walk();
return 0;
}
5 , 观 察 者 模 式 : \red{5,观察者模式:} 5,观察者模式:
定义一对多依赖,目标对象状态改变,多个观察者收到通知并自动更新。