抽象工厂与工厂方法:组合与实施?

这个问题在这里已经有了答案:

  • 工厂,抽象工厂和工厂方法3的答案

  • 抽象工厂

    public interface IMyFactory
    {
        IMyClass CreateMyClass(int someParameter);
    }
    

    用法:

    public class SomeOtherClass
    {
        private readonly IMyFactory factory;
    
        public SomeOtherClass(IMyFactory factory)
        {
            this.factory = factory;
        }
    
        public void DoSomethingInteresting()
        {
            var mc = this.factory.CreateMyClass(42);
            // Do something interesting here
        }
    }
    

    请注意, SomeOtherClass依赖于Composition与IMyFactory实例组合。

    工厂方法

    public abstract class SomeOtherClassBase
    {
        public void DoSomethingInteresting()
        {
            var mc = this.CreateMyClass(42);
            // Do something interesting here
        }
    
        protected abstract IMyClass CreateMyClass(int someParameter)
    }
    

    用法:

    public class SomeOtherClass2 : SomeOtherClassBase
    {   
        protected override IMyClass CreateMyClass(int someParameter)
        {
            // Return an IMyClass instance from here
        }
    }
    

    注意这个例子依赖于继承来工作。

    链接地址: http://www.djcxy.com/p/50123.html

    上一篇: Abstract Factory vs Factory method: Composition vs Inplement?

    下一篇: Design Patterns: Abstract Factory vs Factory Method