博客
关于我
3-工厂模式 - 创建型模式
阅读量:398 次
发布时间:2019-03-05

本文共 3327 字,大约阅读时间需要 11 分钟。

设计模式之禅:工厂模式

在软件开发中,设计模式如同一把精准的手术刀,可以帮助开发者应对各种复杂的软件设计问题。今天我们将探讨其中一种经典的设计模式——工厂模式。

1. 例子

工厂模式的核心思想是一个接口定义了一个创建对象的方法,让子类决定实例化哪个具体的类。这种设计让对象的创建过程被抽象化,使得代码更加灵活和可扩展。

public interface Human {    void getColor();    void talk();}public class YellowHuman implements Human {    @Override    public void getColor() {        System.out.println("YellowHuman is yellow");    }    @Override    public void talk() {        System.out.println("YellowHuman talk");    }}public class WhiteHuman implements Human {    @Override    public void getColor() {        System.out.println("WhiteHuman is white");    }    @Override    public void talk() {        System.out.println("WhiteHuman talk");    }}public class BlackHuman implements Human {    @Override    public void getColor() {        System.out.println("BlackHuman is black");    }    @Override    public void talk() {        System.out.println("BlackHuman talk");    }}public abstract class AbstractHumanFactory {    public abstract 
T createHuman(Class
c);}public class HumanFactory extends AbstractHumanFactory { @Override public
T createHuman(Class
c) { T instance = null; try { instance = (T) Class.forName(c.getName()).newInstance(); } catch (Exception e) { System.out.println("创建人类失败"); } return instance; }}public class NvWa { public static void main(String[] args) { HumanFactory humanFactory = new HumanFactory(); YellowHuman yellowHuman = humanFactory.createHuman(YellowHuman.class); WhiteHuman whiteHuman = humanFactory.createHuman(WhiteHuman.class); BlackHuman blackHuman = humanFactory.createHuman(BlackHuman.class); yellowHuman.getColor(); yellowHuman.talk(); whiteHuman.getColor(); whiteHuman.talk(); blackHuman.getColor(); blackHuman.talk(); }}

2. 定义和特点

工厂方法定义了一个创建对象的接口,让子类决定实例化哪个类。这种设计让对象的创建过程被推迟到子类,具有以下优点:

  • 封装性:调用者无需了解具体的创建逻辑,只需传入类名或字符串即可创建对象。
  • 扩展性:支持轻松添加新类型的对象创建,例如可以通过工厂轻松增加"棕色人种"等新人种。

工厂模式符合以下设计原则:

  • 迪米特原则:工厂类不需要了解具体的产品类。
  • 依赖倒置原则:工厂类只依赖于产品的接口或抽象类。
  • 里氏替换原则:工厂方法的参数是接口或抽象类。

3. 工厂模式的扩展

工厂模式可以根据具体需求进行扩展:

3.1 简单工厂模式

简单工厂模式(静态工厂模式)通过预先定义的工厂类实现对象的创建。其核心代码如下:

public class SimpleFactory implements HumanFactory {    public Human createHuman(String humanType) {        Human human = null;        switch (humanType) {            case "yellow":                human = new YellowHuman();                break;            case "white":                human = new WhiteHuman();                break;            case "black":                human = new BlackHuman();                break;            default:                System.out.println("未识别的人类类型");        }        return human;    }}

3.2 多个工厂模式

在某些场景下,可能需要多个不同的工厂来创建不同类型的对象。可以通过工厂类的注册方式实现动态工厂的选择:

public class FactoryRegistry {    private static Map
factories = new HashMap<>(); public static
T createHuman(String type) { Factory factory = factories.get(type); if (factory != null) { return factory.createHuman(); } else { throw new RuntimeException("未注册的工厂类型"); } } public static void registerFactory(String type, Factory factory) { factories.put(type, factory); }}

工厂模式通过将对象的创建过程抽象化,使得代码更加灵活和可扩展,是解决对象创建问题的优雅解决方案。

转载地址:http://xphwz.baihongyu.com/

你可能感兴趣的文章
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>