常见的设计模式
工厂模式
这个模式有三个对象:工厂、用户、产品;这么说可能还有点抽象,说的具体点,就是当我们
在代码中需要获取一个类的时候,不直接去拿到这个类名,然后new;而是通过一个工厂
类(例如EntityFactory),然后通过给这个工厂类传要创建的类型名字,然后拿到对应生
成的类;这样做的好处是将对象的构造和使用的地方隔离,使之模块化。
例如:
EntityFactory.instance().register_entity(etype, claz)//注册
EntityFactory.instance().create_entity(‘PlayerHero’, None)//使用
单例模式
使内存中只存在一个对象,通常是私有构造函数、静态公共获取函数、私有静态自身成员;创建单例的方式有
懒汉模式、饿汉模式、静态内部类实现等。
#ifndef __SINGLETON__
#define __SINGLETON__
#include<iostream>
#include<string>
#include"Singleton.h"
using namespace std;
class Singleton1 // 懒汉模式
{
private:
static Singleton1* _instance;
Singleton1()=default;
Singleton1(const Singleton1&) = delete;
Singleton1& operator=(const Singleton1&) = delete;
public:
static Singleton1* GetInstance()
{
if (_instance == NULL)
{
_instance = new Singleton1();
}
return _instance;
}
};
Singleton1* Singleton1::_instance;
class Singleton2 // 饿汉模式
{
private:
static Singleton2* _instance;
Singleton2() {};
Singleton2(const Singleton2&) = delete;
Singleton2& operator=(const Singleton2&) = delete;
public:
static Singleton2* GetInstance()
{
if (_instance == NULL)
{
_instance = new Singleton2();
}
return _instance;
}
};
Singleton2* Singleton2::_instance;
class Singleton3 // 局部静态变量实现,还有一种是加锁模式,比较麻烦且耗,需要的百度下就行了
{
private:
Singleton3() {};
public:
static Singleton3& GetInstance()
{
static Singleton3 instance;
return instance;
}
};
#endif // !__SINGLETON__
观察者模式
当一个事件发生时,需要去通知其他订阅者;例如游戏里面常见的领完奖励之后刷新UI界面等等。
策略模式
多种方式打到一种目的,例如网页的登录:手机登录、扫码登录、账号密码登录等,都是为了登录到同一个账号。
代理模式
在真是的某个对象上再包一层代码,可以很方便的扩展其功能;例如游戏中的相机,我们可以在原生相机的基础上包装一层,然后可以在这一层代理里面加一些保护、实现一些原生接口函数的组合功能等。
装饰模式
可以对原来的函数或者类进行扩展;对于类的装饰,可以实现组件式的代码结构,使得各个功能可以和方便的添加与删除,并且代码的逻辑也会很清晰;实现的功能是以组件的形式实现与继承相似的效果。