设计模式-工厂模式

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

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();
    }
}

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
Doris_202313 小时前
代码格式化 使用oxfmt
设计模式·架构·前端框架
Doris_202313 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
Pomelooooo14 小时前
把 git commit 这件事,彻底交给 AI ——一个工程化 /git-commit 命令的设计与落地
设计模式
invicinble15 小时前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
invicinble18 小时前
设计模式(类的拓扑结构)(为什么会产生设计模式,以及什么是设计模式)
linux·服务器·设计模式
PersonalViolet20 小时前
模板方法模式实战:重构Agent工具审批,告别重复代码
设计模式·agent
老码观察20 小时前
设计模式实战解读(五):策略模式——干掉 if-else 的优雅方案
java·设计模式·策略模式
解决问题no解决代码问题21 小时前
设计模式分类介绍
java·开发语言·设计模式
烬羽21 小时前
从 Python List 到 LLM 接口:一条被忽视的 AI 入门捷径
设计模式
我爱cope1 天前
【Agent智能体8 | 反思设计模式-大语言模型反思机制的四个演进阶段】
人工智能·设计模式·语言模型