博客
关于我
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/

你可能感兴趣的文章
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm scripts 使用指南
查看>>
npm should be run outside of the node repl, in your normal shell
查看>>
npm start运行了什么
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
npm 下载依赖慢的解决方案(亲测有效)
查看>>
npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
查看>>
npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
查看>>
npm—小记
查看>>
npm上传自己的项目
查看>>
npm介绍以及常用命令
查看>>
NPM使用前设置和升级
查看>>
npm入门,这篇就够了
查看>>
npm切换到淘宝源
查看>>