Skip to main content
 首页 » 编程设计

n 派生对象的 C# 通用工厂模式(创建所有父类(super class)型)

2024年02月23日1398°冷暖

我有一个通用对象工厂 FactoryBase<T>使用工厂方法:

public abstract class FactoryBase<T> where T : new() 
{ 
    public virtual T CreateInstance() 
    { 
        T thing = new T(); 
 
        // Tweak 'thing' a bit... 
 
        return thing; 
    } 
} 

这非常适合为各种类型创建具体工厂:

public class FruitFactory : FactoryBase<Fruit> 
{ 
    public override Fruit CreateInstance() 
    { 
        Fruit fruit = base.CreateInstance(); 
 
        // Do some Fruit polishing stuff... 
 
        return fruit; 
    } 
} 

但是,如果我想创建一个派生自 Fruit 的工厂类型,该模式就会失效。 :

第一次尝试:(可行,但不正确)

在这里,AppleFactory直接继承FactoryBase<Apple> -- 这是错误的,因为 AppleFactory应该依赖FruitFactory建立一个漂亮的抛光Fruit在此基础上构建我们的 Apple :

// Should inherit FruitFactory, not FactoryBase 
public class AppleFactory : FactoryBase<Apple> 
{ 
    public override Apple CreateInstance() 
    { 
        Apple apple = base.CreateInstance(); 
 
        // FruitFactory is left out above, so... 
        // ...we have to do all the Fruit polishing stuff... 
        // ... and any apple stuff... 
 
        return apple; 
    } 
} 

第二次尝试:(完全失败)

继承FruitFactory显然是一个错误,因为它是非通用的并返回 Fruit不是Apple :

// COMPILE ERRORS 
public class AppleFactory : FruitFactory 
{ 
    public override Apple CreateInstance()  // ERROR: Override method must return Fruit 
    { 
        Apple apple = base.CreateInstance(); // ERROR: FruitFactory returns a Fruit 
        return apple; 
    } 
} 

“丑陋”的解决方案?

通过重构 FruitFactory进入通用 FruitFactory<T>我可以创建一个正确派生的 AppleFactory :

public abstract class FruitFactory<T> where T : Fruit, new() 
{ 
    public override T CreateInstance() 
    { 
        T fruit = (T)base.CreateInstance(); 
 
        // Do some Fruit polishing stuff... 
 
        return fruit; 
    } 
} 
 
// AppleFactory that property calls FruitFactory<Apple> 
public class AppleFactory : FruitFactory<Apple> 
{ 
    public override Apple CreateInstance() 
    { 
        Apple apple = base.CreateInstance(); 
 
        // ... ONLY apple stuff needed!!! 
 
        return apple; 
    } 
} 

我故意制作 FruitFactory<T>抽象,因为客户端代码调用 FruitFactory<Fruit> 看起来丑陋且多余.因此,我提供了一个非通用的 FruitFactory不需要任何 body 即可发挥全部功能:

// Concrete FruitFactory 
public class FruitFactory : FruitFactory<Fruit> { } 

投诉:

每次我需要一个更多派生类型的工厂时,我必须将相应基类型的工厂转换为抽象泛型。

换句话说,如果我有一个 FooFactory我必须将其转换为 FooFactory<T>为了创造DerivedFooFactory : FooFactory<DerivedFoo>

同时,我必须制作新的混凝土FooFactory : FooFactory<Foo> .

或者...我可以直接使用通用工厂:

var fruitFactory = new FruitFactory<Fruit>(); // Double-Fruity! sigh... 

有没有更简洁的方法来创建 AppleFactory首先得到一个 Apple从一个FruitFactory不需要继承链中每个“中间人”类型的通用类?

注意:我真的不想使用反射或复杂的方案。

请您参考如下方法:

我仍然无法理解您的问题,但我认为可以通过制作 FruitFactory<T> 来解决。非抽象:

public class FruitFactory<T> : FactoryBase<T> where T : Fruit, new() 
{         
    // I'm assuming this is in FactoryBase<T> 
    public override T CreateInstance() 
    { 
        return new T(); 
    } 
} 

然后您可以从中派生并覆盖 CreateInstance当你写 AppleFactory .