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

你可能感兴趣的文章
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>
Node-RED中使用node-random节点来实现随机数在折线图中显示
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>
Node-RED中使用node-red-contrib-image-output节点实现图片预览
查看>>
Node-RED中使用node-red-node-ui-iframe节点实现内嵌iframe访问其他网站的效果
查看>>
Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
Node-RED中通过node-red-ui-webcam节点实现访问摄像头并截取照片预览
查看>>
node-request模块
查看>>