设计模式-创建型模式(单例、工厂、建造、原型)

这篇具有很好参考价值的文章主要介绍了设计模式-创建型模式(单例、工厂、建造、原型)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Concept-概念前置

设计模式:软件设计中普遍存在(反复出现)的各种问题,所提出的解决方案。

面向对象三大特性:封装、继承、多态。

面向对象设计的SOLID原则:
(1)开放封闭原则:一个软件实体如类、模块和函数应该对扩展开放,对修改关闭。即软件实体应尽量在不修改原有代码的情况下进行扩展。

(2)里氏替换原则:所有引用父类的地方必须能透明地使用其子类的对象。

(3)依赖倒置原则:高层模块不应该依赖低层模块,二者都应该依赖其抽象; 抽象不应该依赖细节;细节应该依赖抽象。

(4)接囗隔离原则:使用多个专门的接口,而不使用单一的总接口,即客户端不应该依赖那些它不需要的接口。
(5)单一职责原则:不要存在多于一个导致类变更的原因,即一个类只负责一项职责。
 

举个例子,可能有不止一块代码调用到该实体,这时候去修改实体里的代码,就很可能引起其他模块会出现问题,当模块关联较多时就会引起不必要的工作量,这是1;

原方法支持父类,当我们在基础上加或修改功能而衍生的子类也应当符合,这是2;

要针对接口编程, 而不是针对实现编程,实现上也就是对底层的依赖按接口格式去写,再实现,而不是随意修改参数格式,即3。

创建型模式

简单工厂模式,工厂方法模式,抽象工厂模式,创建者模式,原型模式,单例模式。

创建型模式(Creational Pattern) 一种用于 创建对象 的设计模式。它们包含一些通用的方法,更加灵活地创建对象,且 封装 了对象的实例化过程
工厂模式(Factory Pattern)

用于根据 客户端需求动态创建 对象。

(包括简单工厂模式,工厂方法模式,抽象工厂模式)

单例模式(Singleton Pattern)

用于确保一个类 只有一个 实例,并提供对该实例的全局访问点。它通常被用于管理共享资源或者限制系统中某些类的实例数量。

建造者模式(Builder Pattern)

用于将一个复杂对象的 构建过程分离 成多个简单的步骤,从而可以灵活地组合和构建不同的对象。它通常被用于创建复杂的对象,比如包含多个组件或者配置项的对象。

原型模式(Prototype Pattern) 用于 复制或克隆 已有的对象,从而创建新的对象。它通过克隆现有对象来创建新对象,从而避免了昂贵的初始化操作。

工厂模式

Factory Pattern

简单工厂模式(Simple Factory Pattern):简单工厂模式是一种基本的工厂模式,通常由一个工厂类根据传入的参数动态决定创建哪种产品类的实例。(简单而言:一个工厂类根据传入参数创建哪个类实例)

场景:适用于对象较少且产品等级结构稳定的情况。 

Characters: 工厂角色(Factory) 抽象产品角色(Product) 具体产品角色(Concrete Product)
class Product:
    def use(self):
        pass


class ConcreteProductA(Product):
    def use(self):
        print("Using product A.")


class ConcreteProductB(Product):
    def use(self):
        print("Using product B.")


class Factory:
    @staticmethod
    def create_product(product_type):
        if product_type == "A":
            return ConcreteProductA()
        elif product_type == "B":
            return ConcreteProductB()


product_a = Factory.create_product("A")
product_a.use()   # 输出:Using product A.

product_b = Factory.create_product("B")
product_b.use()   # 输出:Using product B.
工厂方法模式(Factory Method Pattern):将实际创建对象的工作推迟到子类中完成。可以在不修改工厂类的情况下,增加新的产品系列和产品等级结构。(简单而言:工厂类抽象化,将增改操作下发给子类)

场景: 工厂方法模式适用于对象数量较多且产品等级结构较为复杂的情况。

Characters: 工厂角色(Factory) 具体工厂角色(Concrete Factory) 抽象产品角色(Product) 具体产品角色(Concrete Product)
class Product:
    def use(self):
        pass


class ConcreteProductA(Product):
    def use(self):
        print("Using product A.")


class ConcreteProductB(Product):
    def use(self):
        print("Using product B.")


class Factory:
    def create_product(self):
        pass


class ConcreteFactoryA(Factory):
    def create_product(self):
        return ConcreteProductA()


class ConcreteFactoryB(Factory):
    def create_product(self):
        return ConcreteProductB()


factory_a = ConcreteFactoryA()
product_a = factory_a.create_product()
product_a.use()  # 输出:Using product A.

factory_b = ConcreteFactoryB()
product_b = factory_b.create_product()
product_b.use()  # 输出:Using product B.

抽象工厂模式(Abstract Factory Pattern):是一种将工厂类进行抽象化的进一步改进,它使用了对象组合的方式来构建不同的产品族。(工厂抽象化,组合各种产品,有点像工厂方法模式的不同类方法组合)

场景: 抽象工厂模式可以同时创建多个不同的产品,且这些产品之间存在着一定的关联性。

Characters: 工厂角色(Factory) 具体工厂角色(Concrete Factory) 抽象产品角色(Product) 具体产品角色(Concrete Product) 客户端(Client)文章来源地址https://www.toymoban.com/news/detail-476834.html

class ProductA:
    def use(self):
        pass


class ConcreteProductA1(ProductA):
    def use(self):
        print("Using product A1.")


class ConcreteProductA2(ProductA):
    def use(self):
        print("Using product A2.")


class ProductB:
    def operate(self):
        pass


class ConcreteProductB1(ProductB):
    def operate(self):
        print("Operating product B1.")


class ConcreteProductB2(ProductB):
    def operate(self):
        print("Operating product B2.")


class Factory:
    def create_product_a(self):
        pass

    def create_product_b(self):
        pass


class ConcreteFactory1(Factory):
    def create_product_a(self):
        return ConcreteProductA1()

    def create_product_b(self):
        return ConcreteProductB1()


class ConcreteFactory2(Factory):
    def create_product_a(self):
        return ConcreteProductA2()

    def create_product_b(self):
        return ConcreteProductB2()


factory_1 = ConcreteFactory1()
product_a1 = factory_1.create_product_a()
product_a1.use()  # 输出:Using product A1.
product_b1 = factory_1.create_product_b()
product_b1.operate()  # 输出:Operating product B1.

factory_2 = ConcreteFactory2()
product_a2 = factory_2.create_product_a()
product_a2.use()  # 输出:Using product A2.
product_b2 = factory_2.create_product_b()
product_b2.operate()  # 输出:Operating product B2.

单例模式

Singleton Pattern

保证一个类仅有一个实例,并提供访问该实例的全局访问点。
class Singleton:
    __instance = None

    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = object.__new__(cls)
        return cls.__instance


s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # 输出:True =》 说明唯一性

建造者模式

Builder Pattern

将一个复杂对象的构建过程分离成多个简单的步骤
场景: 灵活地组合和构建不同的对象。

Characters:
    产品类(Product) 抽象建造者类(Builder)
    具体建造者类(ConcreteBuilder) 指挥者类(Director)
class Product:
    def __init__(self):
        self.part_a = None
        self.part_b = None


class Builder:
    def build_part_a(self):
        pass

    def build_part_b(self):
        pass

    def get_result(self):
        pass


class ConcreteBuilder1(Builder):
    def __init__(self):
        self.product = Product()

    def build_part_a(self):
        self.product.part_a = "Part A1"

    def build_part_b(self):
        self.product.part_b = "Part B1"

    def get_result(self):
        return self.product


class ConcreteBuilder2(Builder):
    def __init__(self):
        self.product = Product()

    def build_part_a(self):
        self.product.part_a = "Part A2"

    def build_part_b(self):
        self.product.part_b = "Part B2"

    def get_result(self):
        return self.product


class Director:
    def __init__(self, builder):
        self.builder = builder

    def construct(self):
        self.builder.build_part_a()
        self.builder.build_part_b()

        return self.builder.get_result()


builder_1 = ConcreteBuilder1()
director_1 = Director(builder_1)
product_1 = director_1.construct()
print(f"Product 1: {product_1.part_a}, {product_1.part_b}")  # 输出:Product 1: Part A1, Part B1

builder_2 = ConcreteBuilder2()
director_2 = Director(builder_2)
product_2 = director_2.construct()
print(f"Product 2: {product_2.part_a}, {product_2.part_b}")  # 输出:Product 2: Part A2, Part B2

原型模式

Prototype Pattern

允许通过复制现有对象来创建新的对象,而无需重新实例化。

Think: 定义一个抽象原型类,包含了用于复制自身的抽象方法 clone()。然后,定义具体的原型类。在客户端代码中,可以通过调用具体对象 clone() 方法来创建新的对象,而无需重新实例化。(注意深浅拷贝问题)
import copy


class Prototype:
    def clone(self):
        return copy.deepcopy(self)


class ConcretePrototype1(Prototype):
    def __init__(self, attr):
        self.attr = attr


class ConcretePrototype2(Prototype):
    def __init__(self, attr):
        self.attr = attr


if __name__ == '__main__':
    prototype_1 = ConcretePrototype1("attr_1")
    prototype_2 = ConcretePrototype2("attr_2")

    clone_1 = prototype_1.clone()
    clone_2 = prototype_2.clone()

    print(f"Original: ({prototype_1.attr}, {prototype_2.attr})")  # 输出:Original: (attr_1, attr_2)
    print(f"Clone: ({clone_1.attr}, {clone_2.attr})")  # 输出:Clone: (attr_1, attr_2)

到了这里,关于设计模式-创建型模式(单例、工厂、建造、原型)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • JavaScript设计模式(二)——简单工厂模式、抽象工厂模式、建造者模式

    个人简介 👀 个人主页: 前端杂货铺 🙋‍♂️ 学习方向: 主攻前端方向,正逐渐往全干发展 📃 个人状态: 研发工程师,现效力于中国工业软件事业 🚀 人生格言: 积跬步至千里,积小流成江海 🥇 推荐学习:🍍前端面试宝典 🍉Vue2 🍋Vue3 🍓Vue2/3项目实战 🥝Node.js🍒

    2024年02月10日
    浏览(28)
  • 万字解析设计模式之原型模式与建造者模式

    原型模式是一种创建型设计模式,其目的是使用已有对象作为原型来创建新的对象。 原型模式的核心是克隆 ,即通过复制已有对象来创建新对象,而不是通过创建新对象的过程中独立地分配和初始化所有需要的资源。这种方式可以节省创建对象的时间和资源,特别是在创建

    2024年02月06日
    浏览(31)
  • 【软件设计模式——单例模式和建造者模式】

    简述 单例模式是一种创建型设计模式,它保证一个类只有一个实例,并提供全局访问点。这意味着在整个应用程序中,只能存在一个该类的对象实例。 主要特点 一个类只有一个实例对象。 提供一个全局访问点,使其他对象可以通过该访问点访问到唯一的实例。 优点 避免了

    2024年02月12日
    浏览(26)
  • 【设计模式】单例模式、工厂方法模式、抽象工厂模式

    1. 单例模式 (Singleton Pattern): 场景: 在一个应用程序中,需要一个全局唯一的配置管理器,确保配置信息只有一个实例。 2. 工厂方法模式 (Factory Method Pattern): 场景: 创建一组具有相似功能但具体实现不同的日志记录器。 3. 抽象工厂模式 (Abstract Factory Pattern): 场景: 创建不同

    2024年01月15日
    浏览(41)
  • 结构型设计模式-单例模式/工厂模式/抽象工厂

    创建型设计模式-单例模式/工厂模式/抽象工厂 行为型设计模式:模板设计模式/观察者设计模式/策略设计模式 C#反射机制实现开闭原则的简单工厂模式 设计模式可以分为三种类型: 创建型设计模式、结构型设计模式和行为型设计模式 。 创建型设计模式:这些模式涉及到 对

    2024年02月11日
    浏览(39)
  • 设计模式(单例模式,工厂模式),线程池

    目录 什么是设计模式? 单例模式 饿汉模式 懒汉模式 工厂模式 线程池 线程池种类 ThreadPoolExcutor的构造方法: 手动实现一个线程池  计算机行业程序员水平层次不齐,为了 让所有人都能够写出规范的代码, 于是就有了设计模式, 针对一些典型的场景,给出一些典型的解决方案 单例

    2024年02月11日
    浏览(25)
  • 【前端知识】JavaScript——设计模式(工厂模式、构造函数模式、原型模式)

    工厂模式是一种众所周知的设计模式,广泛应用于软件工程领域,用于抽象创建特定对象的过程。 优点:可以解决创建多个类似对象的问题 缺点:没有解决对象标识问题(即新创建的对象是什么类型) 示例: 构造函数模式与工厂模式相比,没有显式地创建对象,其属性和方

    2024年02月15日
    浏览(33)
  • Java设计模式---单例 工厂 代理模式

    单例模式是设计模式中的一种,属于创建型模式。在软件工程中,单例模式确保一个类只有一个实例,并提供一个全局访问点。这种模式常用于那些需要频繁实例化然后引用,且创建新实例的开销较大的类,例如数据库连接池、缓存管理等。 意图 :保证一个类仅有一个实例

    2024年01月24日
    浏览(36)
  • Python入门【​编辑、组合、设计模式_工厂模式实现 、设计模式_单例模式实现、工厂和单例模式结合、异常是什么?异常的解决思路 】(十七)

    👏作者简介:大家好,我是爱敲代码的小王,CSDN博客博主,Python小白 📕系列专栏:python入门到实战、Python爬虫开发、Python办公自动化、Python数据分析、Python前后端开发 📧如果文章知识点有错误的地方,请指正!和大家一起学习,一起进步👀 🔥如果感觉博主的文章还不错的

    2024年02月14日
    浏览(26)
  • java基础之设计模式(单例模式,工厂模式)

    是一种编码套路 单例模式 一个类只能创建一个实例 饿汉式 直接创建唯一实例 缺点: 有可能浪费空间 懒汉式 在获取实例是创建唯一对象 缺点: 线程效率慢 懒汉式-进阶版 在懒汉式的基础上,利用同步代码块结合二次校验提高执行效率 工厂模式 是一种底层技术,通常用于底层框

    2024年01月18日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包