using namespace std;
//原型模式(clone出和原对象内容一样的对象)
//原型工厂
class ProtoType {
protected:
string m_name;
public:
ProtoType() {}
ProtoType(string name) :m_name(name) {}
//clone方法利用ProtoType的默认拷贝构造方法,构造出新对象
virtual ProtoType* clone() = 0;
virtual string getName() = 0;
};
class Media :public ProtoType {
public:
Media(string name):ProtoType(name) {}
Media(const Media& media) { m_name = media.m_name; }
ProtoType* clone() {
//下面这句调用了Media(const Media& media)
return new Media(*this);
}
string getName() {
return m_name;
}
};
void testProtoType() {
ProtoType* protoType = new Media(“huahua”);
ProtoType* protoType1=protoType->clone();
cout << protoType1->getName() << endl;
delete protoType;
delete protoType1;
protoType = nullptr;
protoType1 = nullptr;
}
//适配器模式(对象适配,类适配)
//目标类
class RobotTarget {
public:
virtual void cry() = 0;
virtual void move() = 0;
};
//被适配类
class DogAdaptee {
public:
virtual void wang() {
cout << “wangwang” << endl;
}
virtual void run() {
cout << “dog is running” << endl;
}
};
//类适配类(类适配需要继承目标类与被适配类)
class ClassDogAdapter :public RobotTarget,public DogAdaptee{
public:
virtual void cry() {
wang();
}
virtual void move() {
run();
}
};
//对象适配类(对象适配需要继承目标类,将被适配类作为属性)
class ObjectDogAdapter :public RobotTarget {
private:
DogAdaptee* m_dogAdaptee;
public:
ObjectDogAdapter(DogAdaptee* dogAdaptee) :m_dogAdaptee(dogAdaptee) {}
virtual void cry() {
m_dogAdaptee->wang();
}
virtual void move() {
m_dogAdaptee->run();
}
};
//测试类适配类
void testClassDogAdapter() {
RobotTarget* robotTarget = new ClassDogAdapter;
robotTarget->cry();
robotTarget->move();
delete robotTarget;
robotTarget = nullptr;
}
//测试对象适配类
void testObjectDogAdapter() {
DogAdaptee* dogAdaptee = new DogAdaptee;
RobotTarget* robotTarget = new ObjectDogAdapter(dogAdaptee);
robotTarget->cry();
robotTarget->move();
delete dogAdaptee;
dogAdaptee= nullptr;
delete robotTarget;
robotTarget = nullptr;
}
//桥接模式
class Color {
public:
virtual void draw() = 0;
};
class Blue :public Color {
void draw() {
cout << “blue” << endl;
}
};
//桥接抽象层(将被桥接对象作为自己的属性)
class Bridging {
protected:
Color* m_color;
public:
Bridging(Color* color) :m_color(color) {}
virtual void paint() = 0;
};
//桥接具体层
class SonBridging :public Bridging {
public:
SonBridging(Color* color) :Bridging(color) {}
void paint() {
m_color->draw();
}
};
//测试桥接模式
void testBridging() {
Color* color = new Blue();
Bridging* bridging = new SonBridging(color);
bridging->paint();
delete color;
delete bridging;
color = nullptr;
bridging = nullptr;
}
int main() {
//测试原型
//testProtoType();
//测试类适配类
//testClassDogAdapter();
//测试对象适配类
//testObjectDogAdapter();
//测试桥接模式
testBridging();
return 0;
}