Abstract Factory, Factory Method, Builder

后端 未结 6 1136
清歌不尽
清歌不尽 2021-01-30 09:21

It may seem as if this is question is a dupe, but please bear with me - I promise I\'ve read the related posts (and the GOF book).

After everything I\'ve read, I still

6条回答
  •  后悔当初
    2021-01-30 09:40

    Abstract Factory is particularly helpful for test driven development and reducing coupling.

    For example, in C#:

    public class Worker
    {
        public IConsumerFactory Factory { get; set; }
    
        private IResource resource;
    
        public DoWork()
        {
            IConsumer consumer = Factory.CreateConsumer();
            consumer.Consume(resource);
        }
    }
    
    public interface IConsumerFactory
    {
        IConsumer CreateConsumer();
    }
    
    public interface IConsumer
    {
        void Consume(IResource resource);
    }
    
    public class DefaultConsumerFactory : IConsumerFactory
    {
        public IConsumer CreateConsumer()
        {
            return new DefaultConsumer();
        }
    }
    
    public class DefaultConsumer : IConsumer
    {
        public void Consume(IResource resource)
        {
          ... Do Work ...
        }
    }
    

    This way, you can use dependency injection to inject the default implementations for production code, and then you can easily mock the factory and the objects it creates.

提交回复
热议问题