设计模式第2弹:工厂方法模式

简介: type ComputerProduct struct{}// 实现工厂方法func (computer ComputerProduct) GetInformation() string { return "电脑,官方称呼计算机,主要用于进行数据运算的一台机器。"}

1、 工厂方法模式概述
工厂方法模式是一种创建模式,又被称为虚拟构造子模式(Virtual Constructor)或者多态性工厂模式(Polymoriphoic Factory)。工厂方法模式是目标是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中。

1.1、 工厂方法模式核心组件
工厂方法模式是在简单工厂模式上的改进,主要包含如下几个角色及组件

抽象工厂(Creator):整个工厂模式的核心角色,它与应用无关,主要在创建模式中规范和产品对应的工厂对象的标准化定义。
具体工厂(Concrete Creator):实现了抽象工厂的具体工厂类,该类型是和应用直接交互的具体实现类,在应用程序中调用,用于创建产品对象。
抽象产品(Product):工厂方法模式创建的所有类型的超级父类,该类型和具体业务有关,用于规范工厂方法模式中创建的方法对象具备的公共特征行为。
具体产品(Concrete Product):该类型实现了抽象产品 父类,是工厂方法模式中具体创建的实例对象。

1.2、 工厂方法模式优缺点

优点:
在简单工厂模式上的改进,核心工厂类不再负责所有产品的构建,而是将具体的工作交给子类进行实现,不再接触和业务相关的具体细节,如此进一步抽象的结果,最直接的作用就是在满足OCP原则的基础上实现了功能的扩展。

缺点:
软件的水平功能扩展已经非常可观,但是对于新功能扩展,灵活性上稍有欠缺,在横向扩展时如果出现新的业务逻辑就需要更改原有的工厂类型代码予以满足了。

在本章节的代码演示中,为了能用最简洁的逻辑结构说明工厂方法模式,不进行多层构建,大家看代码的时候可以自行拓展。

2、 Java实现
(1) 核心工厂声明

package com.damu.inter;

/**

  • 项目文档: 工厂接口

  • @author 大牧
  • @version V1.0
    /
    public interface IFactory {
    /*
    • 获取具体产品实例的方法
    • @return 返回创建的实例对象
      */
      T product();
      }

(2) 核心产品声明

package com.damu.inter;

/**

  • 项目文档: 产品接口


    *
  • @author 大牧
  • @version V1.0
    */
    public interface IProduct {

    /**

    • 产品类型的公共方法
    • @return 返回产品信息
      */
      String getInformation();
      }

(3) 产品具体实现

为了简洁起见,我们直接实现IProduct接口完成具体产品类的定义,不再进行多层声明。

package com.damu.inter.product.impl;

import com.damu.inter.IProduct;

/**

  • 项目文档: 产品具体实现


    *
  • @author 大牧
  • @version V1.0
    */
    public class PhoneProduct implements IProduct {
    @Override
    public String getInformation() {
     return "电视很NB,报纸很NB,杂志很NB,游戏机很NB,小说很NB,最终都被手机干掉了";
    
    AI 代码解读
    }
    }
    (4) 工厂具体实现

package com.damu.inter.factory.impl;

import com.damu.inter.IFactory;
import com.damu.inter.IProduct;
import com.damu.inter.product.impl.PhoneProduct;

/**

  • 项目文档: 具体工厂


    *
  • @author 大牧
  • @version V1.0
    */
    public class PhoneFactory implements IFactory {
    @Override
    public PhoneProduct product() {
     // 工厂标准方法中,完成指定产品对象的构建
     return new PhoneProduct();
    
    AI 代码解读
    }
    }

package com.damu.inter.factory.impl;

import com.damu.inter.IFactory;
import com.damu.inter.IProduct;
import com.damu.inter.product.impl.ComputerProduct;

/**

  • 项目文档: TODO


    *
  • @author 大牧
  • @version V1.0
    */
    public class ComputerFactory implements IFactory {
    @Override
    public ComputerProduct product() {
     // 工厂方法标注方法:完成对象的创建并返回
     return new ComputerProduct();
    
    AI 代码解读
    }
    }
    (5) 代码测试

package com.damu;

import com.damu.inter.IFactory;
import com.damu.inter.IProduct;
import com.damu.inter.factory.impl.ComputerFactory;
import com.damu.inter.factory.impl.PhoneFactory;
import com.damu.inter.product.impl.ComputerProduct;
import com.damu.inter.product.impl.PhoneProduct;

/**

  • 项目文档: TODO


    *
  • @author 大牧
  • @version V1.0
    */
    public class Main {

    public static void main(String[] args) {

     // 创建工厂对象
     IFactory<IProduct> phoneFactory = new PhoneFactory();
     // 通过工厂穿件具体对象
     IProduct phoneProduct = phoneFactory.product();
     System.out.println(phoneProduct.getInformation());
    
     // 创建工厂对象
     IFactory<IProduct> computerFactory = new ComputerFactory();
     // 通过工厂创建具体对象
     IProduct computerProduct = computerFactory.product();
     System.out.println(computerProduct.getInformation());
    
    AI 代码解读

    }
    }
    在测试代码中,我们可以观察到在获取到统一的工厂实例对象后,通过工厂实例创建的具体产品对象,是根据在构建的时候的具体工厂决定的,也就是具体工厂和具体产品之间的业务关系是比较紧密的,运行结果如下:

/Library/../classes com.damu.Main
电视很NB,报纸很NB,杂志很NB,游戏机很NB,小说很NB,最终都被手机干掉了
电脑,官方称呼计算机,主要用于进行数据运算的一台机器。

3、 Python实现
还原Java工厂方法模式的实现

"""
工厂方法模式
"""
import abc

class IFactory(metaclass=abc.ABCMeta):
"""工厂接口"""

@abc.abstractmethod
def product(self):
    raise NotImplementedError("该方法必须在工厂子类中实现")
AI 代码解读

class IProduct(metaclass=abc.ABCMeta):
"""产品接口"""

@abc.abstractmethod
def get_information(self):
    raise NotImplementedError("该方法必须在产品子类中实现")
AI 代码解读

class PhoneProduct(IProduct):
"""手机产品"""

def get_information(self):
    return "电视很NB,报纸很NB,杂志很NB,游戏机很NB,小说很NB,最终都被手机干掉了"
AI 代码解读

class ComputerProduct(IProduct):
"""电脑产品"""

def get_information(self):
    return "电脑,官方称呼计算机,主要用于进行数据运算的一台机器"
AI 代码解读

class PhoneFactory(IFactory):
"""手机工厂"""

def product(self):
    """生产手机对象的工厂方法"""
    return PhoneProduct()
AI 代码解读

class ComputerFactory(IFactory):
"""电脑工厂"""

def product(self):
    """生产电脑对象的工厂方法"""
    return ComputerProduct()
AI 代码解读

if name == "main":
"""测试代码"""

# 创建工厂实例
phoneFactory = PhoneFactory()
# 创建产品
phone = phoneFactory.product()
print(phone.get_information())

# 创建电脑工厂
computerFactory = ComputerFactory()
# 创建产品
computer = computerFactory.product()
print(computer.get_information())
AI 代码解读

4、 Go实现
4.1、 定义工厂及产品接口
3分钟就能明白

package main

import "fmt"

/
定义产品接口
/
type IProduct interface {
// 获取产品信息的方法
GetInformation() string
}

/
定义工厂接口
/
type IFactory interface {
// 生产产品的方法
product() IProduct
}
4.2、 构建具体产品类型

/
定义具体产品:手机、电脑
/
type PhoneProduct struct {}
// 实现工厂方法
func (phone PhoneProduct) GetInformation() string {
return "电视很NB,报纸很NB,杂志很NB,游戏机很NB,小说很NB,最终都被手机干掉了"
}

/
产品:电脑
/
type ComputerProduct struct{}
// 实现工厂方法
func (computer ComputerProduct) GetInformation() string {
return "电脑,官方称呼计算机,主要用于进行数据运算的一台机器。"
}

4.3、 构建具体工厂类型

/
具体工厂:手机工厂
/
type PhoneFactory struct{}
// 实现接口方法
func (phoneFactory PhoneFactory) product() IProduct {
return new(PhoneProduct)
}

/
具体工厂:电脑工厂
/
type ComputerFactory struct{}
// 实现接口方法
func (computerFactory ComputerFactory) product() IProduct {
return new(ComputerProduct)
}
4.4、测试代码

func main() {
// 创建工厂对象
phoneFactory := new(PhoneFactory)
// 创建具体对象
phone := phoneFactory.product()
fmt.Println(phone.GetInformation())

// 创建工厂对象
computerFactory := new(ComputerFactory)
// 创建具体对象
computer := computerFactory.product()
fmt.Println(computer.GetInformation())
AI 代码解读

}

目录
打赏
0
4
4
0
25
分享
相关文章
【设计模式】【创建型模式】工厂方法模式(Factory Methods)
一、入门 什么是工厂方法模式? 工厂方法模式(Factory Method Pattern)是一种创建型设计模式,它定义了一个用于创建对象的接口,但由子类决定实例化哪个类。工厂方法模式使类的实例化延迟
86 16
并发设计模式实战系列(2):领导者/追随者模式
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发设计模式实战系列,第二章领导者/追随者(Leader/Followers)模式,废话不多说直接开始~
62 0
并发设计模式实战系列(1):半同步/半异步模式
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发设计模式实战系列,第一章半同步/半异步(Half-Sync/Half-Async)模式,废话不多说直接开始~
50 0
并发设计模式实战系列(12):不变模式(Immutable Object)
🌟 大家好,我是摘星!🌟今天为大家带来的是并发设计模式实战系列,第十二章,废话不多说直接开始~
47 0
设计模式觉醒系列(04)策略模式|简单工厂模式的升级版
本文介绍了简单工厂模式与策略模式的概念及其融合实践。简单工厂模式用于对象创建,通过隐藏实现细节简化代码;策略模式关注行为封装与切换,支持动态替换算法,增强灵活性。两者结合形成“策略工厂”,既简化对象创建又保持低耦合。文章通过支付案例演示了模式的应用,并强调实际开发中应根据需求选择合适的设计模式,避免生搬硬套。最后推荐了JVM调优、并发编程等技术专题,助力开发者提升技能。
前端必须掌握的设计模式——模板模式
模板模式(Template Pattern)是一种行为型设计模式,父类定义固定流程和步骤顺序,子类通过继承并重写特定方法实现具体步骤。适用于具有固定结构或流程的场景,如组装汽车、包装礼物等。举例来说,公司年会节目征集时,蜘蛛侠定义了歌曲的四个步骤:前奏、主歌、副歌、结尾。金刚狼和绿巨人根据此模板设计各自的表演内容。通过抽象类定义通用逻辑,子类实现个性化行为,从而减少重复代码。模板模式还支持钩子方法,允许跳过某些步骤,增加灵活性。
335 11
并发设计模式实战系列(20):扇出/扇入模式(Fan-Out/Fan-In)(完结篇)
🌟 大家好,我是摘星!🌟今天为大家带来的是并发设计模式实战系列,第二十章,废话不多说直接开始~
66 0
Kotlin教程笔记(51) - 改良设计模式 - 构建者模式
Kotlin教程笔记(51) - 改良设计模式 - 构建者模式
设计模式:工厂方法模式(Factory Method)
工厂方法模式是一种创建型设计模式,通过将对象的创建延迟到子类实现解耦。其核心是抽象工厂声明工厂方法返回抽象产品,具体工厂重写该方法返回具体产品实例。适用于动态扩展产品类型、复杂创建逻辑和框架设计等场景,如日志记录器、数据库连接池等。优点包括符合开闭原则、解耦客户端与具体产品;缺点是可能增加类数量和复杂度。典型应用如Java集合框架、Spring BeanFactory等。
|
6月前
|
「全网最细 + 实战源码案例」设计模式——模式扩展(配置工厂)
该设计通过配置文件和反射机制动态选择具体工厂,减少硬编码依赖,提升系统灵活性和扩展性。配置文件解耦、反射创建对象,新增产品族无需修改客户端代码。示例中,`CoffeeFactory`类加载配置文件并使用反射生成咖啡对象,客户端调用时只需指定名称即可获取对应产品实例。
122 40

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问