- 前言
- 一、设计模式分类
- 二、具体设计模式
- 1.组件协作
- 1.1 Template Method
- 1.2 Strategy
- 1.3 Observer / Event
- 2.单一职责
- 2.1 Decorator
- 2.2 Bridge
- 3.对象创建
- 3.1 Factory Method
- 3.2 Abstract Factory
- 3.3 Prototype
- 3.4 Builder
- 4.对象性能
- 4.1 Singleton
- 4.2 Flyweight
- 5.接口隔离
- 5.1 Facade
- 5.2 Proxy
- 5.3 Mediator
- 5.4 Adapter
- 6.状态变化
- 6.1 Memento
- 6.2 State
- 7.数据结构
- 7.1 Composite
- 7.2 Iterator
- 7.3 Chain of
- 7.4 Resposibility
- 8.行为变化
- 8.1 Command
- 8.2 Visitor
- 9.领域问题
- 9.1 Interpreter
- 总结
前言
设计模式:一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。
一、设计模式分类
1.创造型,结构型,行为型
2.类模式,对象模式
模板方法(Template Method)模式的定义如下:定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。它是一种类行为型模式。
该模式的主要优点如下。
它封装了不变部分,扩展可变部分。它把认为是不变部分的算法封装到父类中实现,而把可变部分算法由子类继承实现,便于子类继续扩展。
它在父类中提取了公共的部分代码,便于代码复用。
部分方法是由子类实现的,因此子类可以通过扩展方式增加相应的功能,符合开闭原则。
class Person {
public:
Person(string name, int age) : name(name), age(age) {
}
virtual ~Person() {
}
string getName() {
return this->name;
}
int getAge() {
return this->age;
}
void eat() {
cout << "我正在吃饭" << endl;
}
virtual void canDo() = 0;
private:
string name;
int age;
};
class Work : public Person {
public:
//构造析构
void canDo() {
cout << "我正在上班" << endl;
}
};
class Student : public Person {
public:
//构造析构
void canDo() {
cout << "我正在上课" << endl;
}
};
1.2 Strategy
1.3 Observer / Event
2.单一职责
2.1 Decorator
2.2 Bridge
3.对象创建
3.1 Factory Method
3.2 Abstract Factory
3.3 Prototype
3.4 Builder
4.对象性能
4.1 Singleton
4.2 Flyweight
5.接口隔离
5.1 Facade
5.2 Proxy
5.3 Mediator
5.4 Adapter
6.状态变化
6.1 Memento
6.2 State
7.数据结构
7.1 Composite
7.2 Iterator
7.3 Chain of
7.4 Resposibility
8.行为变化
8.1 Command
8.2 Visitor
9.领域问题
9.1 Interpreter
总结
至此,所有常见设计模式叙述完毕。(未完待续)



