博客
关于我
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 connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
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三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>