标签: factory-method

工厂方法返回null是否可以?

我想知道这里的最佳做法.如果工厂方法无法创建任何内容,那么返回null是一种好习惯吗?这是一个例子:

ICommand command = CommandFactory.CreateCommand(args);
if (command != null)
    command.Execute();
else
    // do something else if there is no command
Run Code Online (Sandbox Code Playgroud)

NullCommand我想,另一种方法是返回一个或某个东西,但最佳做法是什么?

c# oop design-patterns factory-method

26
推荐指数
1
解决办法
4100
查看次数

物体的工厂方法 - 最佳实践?

这是一个关于使用python从不同形式的相同数据创建类或类型的实例的最佳实践的问题.使用类方法是否更好,或者更好地完全使用单独的函数?假设我有一个用于描述文档大小的类.(注意:这只是一个例子.我想知道创建类实例的最佳方法,而不是描述文档大小的最佳方法.)

class Size(object):
    """
    Utility object used to describe the size of a document.
    """

    BYTE = 8
    KILO = 1024

    def __init__(self, bits):
        self._bits = bits

    @property
    def bits(self):
        return float(self._bits)

    @property
    def bytes(self):
        return self.bits / self.BYTE

    @property
    def kilobits(self):
        return self.bits / self.KILO

    @property
    def kilobytes(self):
        return self.bytes / self.KILO

    @property
    def megabits(self):
        return self.kilobits / self.KILO

    @property
    def megabytes(self):
        return self.kilobytes / self.KILO
Run Code Online (Sandbox Code Playgroud)

我的__init__方法采用以位表示的大小值(位和唯一的位,我想保持这种方式),但是假设我有一个以字节为单位的大小值,我想创建一个类的实例.使用类方法是否更好,或者更好地完全使用单独的函数?

class Size(object):
    """
    Utility object used to describe …
Run Code Online (Sandbox Code Playgroud)

python coding-style decorator factory-method class-method

23
推荐指数
1
解决办法
2万
查看次数

使用JavaScript的设计模式实现的一些示例是什么?

我是一个熟练的程序员,使用JavaScript,但我不是大师.我知道你可以用它做一些非常强大的东西,除了相当基本的DOM操作之外我还没有看到太多东西.我想知道人们是否可以使用JavaScript提供一些传统设计模式概念的例子,例如Factory Method,Singleton等.在什么情况下这些模式将用于网络?

javascript singleton design-patterns strategy-pattern factory-method

17
推荐指数
2
解决办法
6910
查看次数

自动装配由EasyMock工厂方法生成的bean?

我有一个看起来很奇怪的问题.我有以下设置:

界面:

package com.example;

public interface SomeDependency {
}
Run Code Online (Sandbox Code Playgroud)

弹簧组件:

package com.example;

@Component
public class SomeClass {
}
Run Code Online (Sandbox Code Playgroud)

带有由EasyMock生成的模拟bean的spring test配置:

<beans ....>
    <context:component-scan base-package="com.example"/>

    <bean id="someInterfaceMock" class="org.easymock.EasyMock" factory-method="createMock">
        <constructor-arg value="com.example.SomeDependency" />
    </bean> 
</beans>
Run Code Online (Sandbox Code Playgroud)

并进行单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/testconfig.xml")
public class SomeClassTest {

    @Autowired
    SomeClass someClass;

    @Autowired
    SomeDependency someDependency;

    @Test
    public void testSomeClass() throws Exception {
        assertNotNull(someClass);
    }

    @Test
    public void testSomeDependency() throws Exception {
        assertNotNull(someDependency);
    }
}
Run Code Online (Sandbox Code Playgroud)

项目编译并且测试通过没有任何问题,即SomeClass("真实"对象)和SomeDependency(由EasyMock生成的模拟对象)的自动装配成功.

但是,如果我将SomeClass的实现更改为:

@Component
public class SomeClass { …
Run Code Online (Sandbox Code Playgroud)

java spring easymock factory-method autowired

14
推荐指数
1
解决办法
1万
查看次数

switch语句是否适用于工厂方法?C#

我想返回一个接口,并在switch语句中我想设置它.这是一个糟糕的设计吗?

private IResultEntity GetEntity(char? someType)
    {
        IResultEntity entity = null;

        switch (someType)
        {
            case 'L': //life
                entity = new LifeEntity();
                break;
            case 'P': //property
                entity = new PropertyEntity();
                break;
            case 'D': //disability
                entity = new DisabilityEntity();
                break;
            case 'C': //credit card
                entity = new CreditCardEntity();
                break;
        }

        return entity;
    }
Run Code Online (Sandbox Code Playgroud)

c# design-patterns interface factory-method

13
推荐指数
1
解决办法
8354
查看次数

实现通用工厂方法

我已经实施了一项车辆服务,负责维修汽车和卡车等车辆:

public interface IVehicleService
{
    void ServiceVehicle(Vehicle vehicle);   
}

public class CarService : IVehicleService
{
    void ServiceVehicle(Vehicle vehicle)
    {
        if (!(vehicle is Car))
            throw new Exception("This service only services cars")

       //logic to service the car goes here
    }
}
Run Code Online (Sandbox Code Playgroud)

我还有一个车辆服务工厂,负责根据传入工厂方法的车辆类型创建车辆服务:

public class VehicleServiceFactory 
{
    public IVehicleService GetVehicleService(Vehicle vehicle)
    {
        if (vehicle is Car)
        {
            return new CarService();
        }

        if (vehicle is Truck)
        {
            return new TruckService();
        }

        throw new NotSupportedException("Vehicle not supported");
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是这个CarService.ServiceVehicle方法.它接受一个Vehicle理想情况下它应该接受一个Car …

c# generics interface factory-method

10
推荐指数
1
解决办法
1231
查看次数

Spring并在运行时将参数传递给factory-method

方法context.getBean(name,user)的文档说

允许指定显式构造函数参数/工厂方法参数

但无论我做什么(尝试过一切),在最初的逻辑设置中,当初始化期间加载bean时,我会得到这个:

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'fileValidator' defined in
PortletContext resource
[/WEB-INF/classes/context/customer-form-portlet.xml]: Unsatisfied
dependency expressed through constructor argument with index 0 of type
[com.liferay.portal.model.User]: Ambiguous factory method argument
types - did you specify the correct bean references as factory method
arguments?
    org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'fileValidator' defined in
PortletContext resource
[/WEB-INF/classes/context/customer-form-portlet.xml]: Unsatisfied
dependency expressed through constructor argument with index 0 of type
[com.liferay.portal.model.User]: Ambiguous factory method argument
types - did you specify the correct bean …
Run Code Online (Sandbox Code Playgroud)

java spring factory-method

9
推荐指数
4
解决办法
6万
查看次数

如果在引用类之前未调用静态初始化程序,则如何注册java类

我有一个由执行文件处理的类实现的接口,比如搜索或其他什么.

public interface FileProcessorInterface {

    public void processFile(String fileName);

}
Run Code Online (Sandbox Code Playgroud)

然后我对每种文件类型都有不同的实现:

public class TxtProcessor implements FileProcessorInterface {

    @Override public void processFile(String fileName) { //do the work }

}
Run Code Online (Sandbox Code Playgroud)

因此我有处理器的Utilizer,它有一个允许注册每个类的方法,如下所示:

class Utilizer {

Map <String, Class> registered = new HashMap<>();

public void registerClass(String fileExt, Class clazz) {

    registered.put(fileExt, clazz);

}

public void processFile(String fileName) {

    //1) get the registered class from registered map (omitted because easy and not relevant)

    //2) create an instance of the class using reflection (omitted because easy …
Run Code Online (Sandbox Code Playgroud)

java factory-method static-initializer

9
推荐指数
2
解决办法
6483
查看次数

在java中扩展参数化工厂方法

我是OOP的新手并学习设计模式所以我写了一些简单的代码来试用一个Factory方法,一切看起来都不错,除非我想添加另一个子类型.这是迄今为止的代码:

public interface Person {
  public String getDescription();
}

public class Adult implements Person { 
  @Override
  public String getDescription() {
    return "I am an ADULT";
  }
}

public class Child implements Person {
  @Override
  public String getDescription() {
    return "I am a CHILD";
  }
}

public class PersonFactory {
  public Person create(int age) {
    if (age < 18) return new Child();
    return new Adult();
  }
}

public class ClientA {
  public static void main(String[] args) {
    PersonFactory personFactory = new …
Run Code Online (Sandbox Code Playgroud)

java factory-method open-closed-principle solid-principles

9
推荐指数
1
解决办法
467
查看次数

工厂方法模式是否违反开放/封闭原则?

请问工厂方法模式(不要与工厂或抽象工厂模式混淆)违反了开/关的原则

更新:为了澄清,我指的是具体类具有静态工厂方法的场景.例如(这是来自FMP上的维基百科页面):

class Complex 
{
    public static Complex fromCartesian(double real, double imag) {
        return new Complex(real, imag);
    }

    public static Complex fromPolar(double modulus, double angle) {
        return new Complex(modulus * cos(angle), modulus * sin(angle));
    }

    private Complex(double a, double b) {
       //...
    }
}
Run Code Online (Sandbox Code Playgroud)

私有构造函数不会阻止类被子类化,即扩展吗?

是否必须修改类以支持新的工厂方法?例如,如果该类最初只有来自Caresian,后来需要来自thePolar,那么是否必须修改该类才能支持此类?

这两个都不违反开放/封闭吗?

design-patterns factory-method open-closed-principle

8
推荐指数
2
解决办法
2668
查看次数