设计模式学习笔记——创建型模式

xiaoxiao2021-02-28  36

这些设计模式提供了一种在创建对象的同时隐藏创建逻辑,使得程序在判断针对某个给定实例需要创建哪些对象时更加灵活。

创建型模式包括五种设计模式:

工厂模式(Factory Pattern)抽象工厂模式(Abstract Factory Pattern)单例模式(Singleton Pattern)建造者模式(Builder Pattern)原型模式(Prototype Pattern)

下面分别归纳一下这五种设计模式的核心思想:

1、工厂模式:提供统一的接口,根据指定的类型,创建不同的子类对象,返回指向子类对象的基类指针

2、抽象工厂模式:提供统一的接口,根据指定的类型,创建不同的工厂,返回工厂对象的基类指针。其实就是将工厂模式作用于众多的工厂

3、单例模式:这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

        单例模式的实现有一下几种方式:

        3.1、懒汉式

//Java的实现,不要求线程安全 public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } //Java实现,线程安全 public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } //C++静态成员变量的方式,为了保证线程安全,需要加锁 class Singleton { private:     static Singleton* m_instance;     Singleton(){} public:     static Singleton* getInstance(); }; Singleton* Singleton::getInstance() {     if(NULL == m_instance)     {         Lock();         if(NULL == m_instance)         {             m_instance = new Singleton;         }         UnLock();     }     return m_instance; } //C++通过内部静态变量,实现单例模式,在C++11之后,要求编译器保障函数内部静态变量的线程安全性 class SingletonInside { private:     SingletonInside(){} public:     static SingletonInside* getInstance()     {         Lock(); //C++11之后就不需要了         static SingletonInside instance;         UnLock(); //C++11之后就不需要了                return instance;      } }; //Java实现,线程安全,高效率 public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }

        3.2、饿汉式

在类被装载的时候就被主线程进行初始化了,不存在线程的安全性问题

//Java实现 public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } } //C++实现 class SingletonStatic { private: static const SingletonStatic* m_instance; SingletonStatic(){} public: static const SingletonStatic* getInstance() { return m_instance; } }; const SingletonStatic* SingletonStatic::m_instance = new SingletonStatic;

4、建造者模式:一个复杂的基类,用其他被多重继承的基类作为成员变量的类型。这个基类的众多派生类之间相同的成员变量有不同的表现。使用多个简单的对象一步一步构建一个复杂的对象。

5、原型模式:创建的新对象是从另一个对象克隆而来。原型模式主要用在创建全新的对象的时候对对象的数据进行初始化可能需要消耗大量的时间空间的情况。引用 runoob中的例子:一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

转载请注明原文地址: https://www.6miu.com/read-2250203.html

最新回复(0)