本文介绍了工厂模式动态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解工厂模式。如果有很多实现,那么我的工厂模式会有很多if else或switch情况。而且每次我介绍一个新的实现我应该改变我的工厂代码

I am trying to understand factory pattern.If there are many implementation then my factory pattern will have lot of if else or switch cases. And also every time I introduce a new implementation i should change my factory code

如下面的例子中假设如果许多动物实施宠物,我们假设狗鸭正在实施宠物界面如果代码或开关案例,我的工厂接口很多if else else。有没有办法通过带来更多动态方法来解决这个问题?

Like in below examples if lets assume dog duck are implementing Pet interface like tomorrow if many animals implement pet interface my factory frows long with lot of if else else if code or switch case. Is there any way to solve this with bringing more dynamic approach?

package com.javapapers.sample.designpattern.factorymethod;

//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {

    public Pet getPet(String petType) {
        Pet pet = null;

        // based on logic factory instantiates an object
        if ("bark".equals(petType))
            pet = new Dog();
        else if ("quack".equals(petType))
            pet = new Duck();
        return pet;
    }

如果动物增长

if ("bark".equals(petType))
    pet = new Dog();
else if ("quack".equals(petType))
    pet = new Duck();
else if ("mno".equals(petType))
    pet = new MNO();
else if ("jkl".equals(petType))
    pet = new JKL();
else if ("ghi".equals(petType))
    pet = new GHI();
else if ("def".equals(petType))
    pet = new DEF();
......
else if ("abc".equals(petType))
    pet = new ABC();
return pet


推荐答案

我认为有一个动态方法:

I think there is a dynamic approach:


  1. 在您的工厂中,您需要 Map< String,Class<?扩展Pet>>

  2. 在扩展Pet的每个类的静态构造函数中,使用这样的map注册它。

  3. 比创建一个类只是 map.get(pet).newInstance (你必须检查空值,当然)

  1. In your factory you need a Map<String, Class<? extends Pet>>
  2. In static constructor of every class, which extends Pet, register it with such map.
  3. Than creating a class will be just map.get(pet).newInstance ( you'd have to check for nulls, of course)

这篇关于工厂模式动态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 01:02