본문 바로가기
Programming

Factory Method Pattern

Factory Method Pattern

팩토리 메소드 패턴은 오브젝트 생성 방법 중에 하나로 인스턴스화할때 서브클래스에서 어떤 클래스를 인스턴스화 할지 결정한다.

Client에서 IProduct를 멤버로 갖고 Creator 클래스를 통해 IProduct 멤버 생성을 위임함.

용도 : 유연성이 중요한 경우, 서브클래스에서 객체들이 확장되야 하는 경우,

 

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace FactoryMethodPattern

{

// Factory Method Pattern Judith Bishop 2006

 

interface IProduct

{

string ShipFrom();

}

 

class ProductA : IProduct

{

public String ShipFrom()

{

return " from South Africa";

}

}

 

class ProductB : IProduct

{

public String ShipFrom()

{

return "from Spain";

}

}

 

class DefaultProduct : IProduct

{

public String ShipFrom()

{

return "not available";

}

}

 

class Creator

{

public IProduct FactoryMethod(int month)

{

if (month >= 4 && month <= 11)

return new ProductA();

else

if (month == 1 || month == 2 || month == 12)

return new ProductB();

else return new DefaultProduct();

}

}

 

class Program

{

static void Main(string[] args)

{

Creator c = new Creator();

IProduct product;

 

for (int i = 1; i <= 12; i++)

{

product = c.FactoryMethod(i);

Console.WriteLine("Avocados " + product.ShipFrom());

}

Console.ReadKey();

}

}

}