Work & Programming/System Design

[Creational Pattern] - Abstract Factory

자전거통학 2024. 5. 15. 10:06

https://refactoring.guru/design-patterns/abstract-factory

 

Abstract Factory

Solution The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family (e.g., chair, sofa or coffee table). Then you can make all variants of products follow those interfaces. For

refactoring.guru

 

특정 상황에 걸맞는 특정 object의 생성을 관련 factory 확장을 통하여 구현하고자 할때. 

 

=> 각자 경우에 맞는 case code가 한군데 합쳐지는 것이 아닌 각자 concrete 생성 class에서 처리하게 된다.

 

예시

Platform Resolution Handler

Platform Specific UX Handler 

각자에 맞는 factory를 생성하면 해당 factory에서 각 platform에 맞는 관련 생성을 처리한다. 

 

예시 code 

더보기
public class AbstractFactoryDemo
{
    public interface IResolutionHandler
    {
        void Init();
        int GetWidth();
        int GetHeight();
    }
    public class IOSResolutionHandler : IResolutionHandler
    {
        public void Init() { }
        public int GetWidth() { return 0;}
        public int GetHeight() { return 0;}
    }
    public class AndroidResolutionHandler : IResolutionHandler
    {
        public void Init() { }
        public int GetWidth() { return 0;}
        public int GetHeight() { return 0;}
    }



    public interface IHandlerFactory
    {
        IResolutionHandler CreateResolutionHandler();
    }

    public class IOSHandlerFactory : IHandlerFactory
    {
        public IResolutionHandler CreateResolutionHandler()
        {
            return new IOSResolutionHandler();
        }
    }
    public class AndroidHandlerFactory : IHandlerFactory
    {
        public IResolutionHandler CreateResolutionHandler()
        {
            return new AndroidResolutionHandler();
        }
    }





    public void Main()
    {
        bool isAndroid = false;
        IHandlerFactory factory = isAndroid ? new AndroidHandlerFactory() : new IOSHandlerFactory();
        IResolutionHandler handler = factory.CreateResolutionHandler();
        handler.Init();
        handler.GetWidth();
    }
}