设计模式-工厂模式

工厂模式:该模式是将简单工厂模式中的工厂作为一个基类(接口),当需要创建的产品(具体子类实例)增加时,不修改原工厂的创建方法,而是增加一个具体工厂子类,由该子类去创建新增的产品,将产品子类的实例化延迟到工厂子类中。

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface Phone
{
    void Name();
}

public class IPhone : Phone
{
    public void Name()
    {
        Debug.Log("苹果手机");
    }
}

public class AZPhone : Phone
{
    public void Name()
    {
        Debug.Log("安卓手机");
    }
}

这是工厂的实现

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IFactory
{
    Phone Creat();
}

public class IPhoneFactory : IFactory
{
    public Phone Creat()
    {
        return new IPhone();
    }
}

public class AZPhoneFactory : IFactory
{
    public Phone Creat()
    {
        return new AZPhone();
    }
}

优点:降低了耦合性,只需要知道要什么产品,不用管创建过程;

更易于扩展;

缺点:代码复杂度提高

相关推荐
一只旭宝1 小时前
【C++入门精讲22】常见设计模式
c++·设计模式
许彰午9 小时前
38_Java设计模式之装饰器模式
java·设计模式·装饰器模式
geovindu13 小时前
python: Reactor Pattern
开发语言·python·设计模式·反应器模式
workflower14 小时前
基于机器学习的设备故障预测分析方法
人工智能·算法·机器学习·设计模式·语言模型·自然语言处理·重构
迷茫运维路15 小时前
Golang架构目录设计与设计模式教程
设计模式·golang
workflower1 天前
使用大语言模型处理用户需求
大数据·人工智能·设计模式·重构·动态规划
geovindu1 天前
go: Generators Pattern
开发语言·后端·设计模式·golang·生成器模式
GuWenyue1 天前
前端异步请求踩坑?3种方式搞定Ajax数据交互,从XHR到async/await
前端·javascript·设计模式
我登哥MVP2 天前
走进 Gang of Four 设计模式:装饰器模式
java·spring boot·设计模式·装饰器模式
秋漓2 天前
软件设计模式
设计模式