什么是设计模式?
设计模式是软件设计中常见的典型解决方案,可用于解决代码反复出现的设计问题。
设计模式不是算法,算法提供明确的步骤,模式更像是一个蓝图(能看到最终的结果)
设计模式背后的面对设计原则:
封装变化
多用组合,少用继承
针对接口编程,不针对实现编程
为交互对象之间的松耦合而努力
对扩展开放,对修改关闭
设计模式分类(意图)
依赖:陌生的关系,点餐
关联关系:依赖
聚合:拥有,员工
组合:生命周期,一只猫有手
实现:接口,不可以创建对象,哺乳动物
继承:猫
工厂方法:用类的方式去延迟new
#include<iostream>
class Transport
{
public:
virtual ~Transport() {}
virtual void deliver() const = 0;
};
class Truck:public Transport
{
public:
void deliver() const override{
std::cout << "卡车" << std::endl;
}
private:
};
class Ship :public Transport
{
public:
void deliver() const override {
std::cout << "轮船" << std::endl;
}
private:
};
class Logistics
{
public:
virtual ~Logistics() {}
virtual Transport* factory() const = 0;
void doSomething() const {
Transport * t = factory();
t->deliver();
delete t;
}
private:
};
class TruckLogincs :public Logistics {
public:
virtual ~TruckLogincs() {}
virtual Transport* factory() const override{
return new Truck();
}
};
class ShipLogincs :public Logistics {
public:
virtual ~ShipLogincs() {}
virtual Transport* factory() const override {
return new Ship();
}
};
int main() {
Logistics* l1 = new TruckLogincs();
l1->doSomething();
ShipLogincs* s = new ShipLogincs();
s->doSomething();
delete l1;
delete s;
return 0;
}
生成器构造比价复杂的对象
#include<iostream>
#include<vector>
#include<string>
class SimpleHouse {
public:
std::vector<std::string> m_parts;
void printParts() const {
std::cout << "SimpleHouse 包括:\n" << std::endl;
for (size_t i = 0; i < m_parts.size(); i++) {
std::cout << m_parts[i] << std::endl;
}
std::cout << "=================" << std::endl;
}
};
class Builder
{
public:
virtual ~Builder() {};
virtual void makeBaseHouse() = 0;
virtual void makeGarage() = 0;
virtual void makePoll() = 0;
virtual void reset() = 0;
private:
};
class SimpleHouseBuilder:public Builder
{
private:
SimpleHouse* simplehouse;
public:
virtual void makeBaseHouse() override {
simplehouse->m_parts.push_back("BaseHouse");
}
virtual void makeGarage() override {
simplehouse->m_parts.push_back("GarageHouse");
}
virtual void makePoll()override {
simplehouse->m_parts.push_back("PollHouse");
}
virtual ~SimpleHouseBuilder() {
delete simplehouse;
};
void reset() override{
simplehouse = new SimpleHouse();
}
SimpleHouse* getResult() {
SimpleHouse * result = simplehouse;
reset();
return result;
}
private:
};
class Director
{
private:
Builder* m_builder;
public:
void setBuilder(Builder* builder) {
m_builder = builder;
}
void makeSimpleHouse() {
m_builder->makeBaseHouse();
}
void makeFullHouse() {
m_builder->makeBaseHouse();
m_builder->makePoll();
}
~Director() {};
private:
};
void client(Director* d) {
//客户自己设计
SimpleHouseBuilder* si = new SimpleHouseBuilder();
si->makeBaseHouse();
si->makeBaseHouse();
SimpleHouse * house = si->getResult();
house->printParts();
house = si->getResult();
house->printParts();
//主管负责
d->setBuilder(si);
d->makeFullHouse();
delete house;
delete si;
}
int main() {
return 0;
}