OO基础:
抽象
封装
多态
继承
OO原则
封装变化
多用组合,少用继承
针对接口编程,不针对实现编程
为交互对象的松耦合设计而努力
类应该对扩展开放对修改封闭
依赖抽象,不要依赖具体类
单件模式(确保一个类只有一个实例,并提供一个全局访问点。)
单件对象,任何时刻只有一个对象。即让一个类只被实例化一次。
它没有公开的构造器,构造器被声明为私有的。外人想要取得实例,必须请求得到一个实例,而不是自行实例化得到一个实例。类中有一个静态方法,叫做getInstance(),调用它,单件对象立即现身,随时工作,事实上,它可能是这次调用出现的,也有可能是之前就被创建了。
他比全局对象更加优秀:急切实例化VS延迟实例化、通过改造可以成为线程安全的。
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Singelton { public: static Singeton* GetInstance();
private: static Singeton* uniquInstance;
private: Singelton(); };
/*static*/Singleton::uniqueInstance = NULL; |
命令模式
把“请求”封装成对象,以便使用不同的请求、队列、日志来参数化其他对象。命令模式也支持可撤销的操作。
命令对象将动作和接收者包含进对象中。
遥控器类:
class RemoteControl
{
private:
vector<Command*> m_onCommandVec;
vector<Command*> m_offCommandVec;
public:
RemoteControl()
{
//...
}
~RemoteControl()
{
//...
}
public:
void SetCommand(int slot, Command* onCommand, Command* offCommand)
{
m_onCommandVec[slot] = onCommand;
m_offCommandVec[slot] = offCommand;
}
void OnButtonWasPressed(int slot)
{
m_onCommandVec[slot].execute();
}
void OffButtonWasPressed(int slot)
{
m_offCommandVec[slot].execute();
}
};