Abstract Factory vs Factory method: Composition vs Inplement?

This question already has an answer here:

  • Factory, Abstract Factory and Factory Method 3 answers

  • Abstract Factory

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

    Usage:

    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
        }
    }
    

    Notice that SomeOtherClass relies on Composition to be composed with an IMyFactory instance.

    Factory Method

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

    Usage:

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

    Notice that this example relies on inheritance to work.

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

    上一篇: 让setter返回“this”是不好的做法吗?

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