2012-12-31 3 views
3

내 프로그램에서 일부 개체는 다른 개체 (종속성)가 필요하며 Factory는 내 창조적 인 패턴으로 사용하고 있습니다.공장 패턴은이 방법으로 사용해도 괜찮습니까?

이제 간단한 종속성 문제를 어떻게 해결할 수 있습니까?

이것은 내 문제를 해결하기 위해 내가 수행 한 예입니다. Create 메소드에 필요한 객체를 보내는 것이 끔찍한 일이 아닌지 알고 싶습니다.

//AbstractBackground 
// - SpecialBackground 
// - ImageBackground 
// - NormalBackground 
class Screen{ 
    List<AbstractBackground> list; 
    Cursor cursor; 
    ContentManager content; 

    public void load(string[] backgroundTypes){ 
     //is this okay? ---------------> 
     AbstractBackground background = BackgroundFactory.Create(backgroundTypes[0], cursor, content); 
     list.add(background); 
    } 
} 

class BackgroundFactory{ 
    static public AbstractBackground Create(string type, Cursor cursor, ContentManager content){ 

     if(type.Equals("special")){ 
      return new SpecialBackground(cursor, content); 
     } 

     if(type.Equals("image")){ 
      return new ImageBackground(content); 
     } 

     if(type.Equals("normal")){ 
      return new NormalBackground(); 
     } 
    } 
} 
+5

http://codereview.stackexchange.com에 더 적합 – Leri

+0

왜 잘못 되었습니까? 그렇지 않습니다. –

+0

실생활 예제에서 공장 패턴에 대한 많은 경험이 없으므로 그 사실을 알고 싶었습니다. – OsakaHQ

답변

4

간단한 답변입니다. 이것을 추상적으로 생각하면 create 메소드를 통해 생성자에 객체를 주입합니다. 이 기술에 문제가 없으며 내가 권장하는 것입니다.

나중에 구현을 변경해야하는 경우 필요에 따라 아무 것도 만들지 않고 다른 작성 메소드를 만들 수 있습니다.

1

의존성 트리가 커지면 생성하는 팩토리 메소드가 복잡해질 것이라는 점을 제외하고는 코드에 너무 추한 것은 없습니다. 다양하고 명확한 종속성을 가진 유형을 분해하려면 IoC 기반 공장을 선택하는 것이 좋습니다. 컨테이너에 종속성을 등록하면 필요한 종속성을 가진 자동 삽입 된 생성자를 갖게됩니다.

+0

예를 들어 물어봐도 될까요? 나는 많은 예제를 만났지만 일부는 단순한 방법이나 예제를 해결하기에는 너무 복잡하여 내가하고 싶은 것을 해결할 수 있을지 전혀 모른다. – OsakaHQ

+0

@ user658091 아키텍처가 단순하게 유지되어야한다면 체재하십시오. 말했듯이 지금은 코드에 아무런 문제가 없습니다. –

5

더 많은 유형이 추가되면 기능적이지만 번거로울 수 있습니다.

enum BackgroundFactoryType 
{ 
    Special, 
    Image, 
    Normal, 
} 

static class BackgroundFactory{ 

    static Dictionary<BackgroundFactoryType, Func<Cursor, ContentManager, AbstractBackground>> constructors; 

    static BackgroundFactory() 
    { 
    //initialize the constructor funcs 
    constructors = new Dictionary<BackgroundFactoryType, Func<Cursor, ContentManager, AbstractBackground>>(); 
    constructors.Add(BackgroundFactoryType.Special, (cursor, content) => new SpecialBackground(cursor, content)); 
    constructors.Add(BackgroundFactoryType.Image, (_, content) => new ImageBackground(content)); 
    constructors.Add(BackgroundFactoryType.Normal, (_, __) => new NormalBackground()); 
    } 

    static public AbstractBackground Create(BackgroundFactoryType type, Cursor cursor, ContentManager content) 
    { 
    if (!constructors.ContainsKey(type)) 
     throw new ArgumentException("the type is bogus"); 

    return constructors[type](cursor, content); 
    } 
} 

또는 당신은 간단하게 할 수있는 :
간단한 공장 내 개인 취향에 따라 구현 될

는 그냥 소요
static class BackgroundFactory{ 

    static public AbstractBackground Create(BackgroundFactoryType type, Cursor cursor, ContentManager content) 
    { 
    switch (type) 
    { 
     case BackgroundFactoryType.Special: 
     return new SpecialBackground(cursor, content); 
     case BackgroundFactoryType.Image: 
     return new ImageBackground(content); 
     case BackgroundFactoryType.Normal: 
     return new NormalBackground(); 
     default: 
     throw new ArgumentException("the type is bogus"); 
    } 
    } 
} 

이 방법의 하나의 좋은 부작용이된다 이 일을 하드 코드 대신 구동시키는 약간의 작업.

+0

'BackgroundFactory'에는 정적 멤버 만 있기 때문에'static'으로 표시하면 안됩니까? – Leri

+0

예, 생성자 사전도 마찬가지입니다. :) – SWeko

관련 문제