c++设计模式-原型模式(clone出和原对象内容一样的对象),适配模式(类适配,对象适配),桥接模式(将被桥接对象作为自己的属性)

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值