Skip to content

Instantly share code, notes, and snippets.

@jwChung
Last active April 3, 2016 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwChung/d16514418593dbdd32d9e6ab349c6600 to your computer and use it in GitHub Desktop.
Save jwChung/d16514418593dbdd32d9e6ab349c6600 to your computer and use it in GitHub Desktop.
Factory Method vs Abstract Factory
using System;
namespace ClassLibrary3
{
public interface IProduct
{
}
public class Foo : IProduct
{
}
public class Bar : IProduct
{
}
/*
* Factory Method 패턴: 상속(Inheritance)기반
* - 인스턴스 만드는 일을 서브클래스에게 위임
*/
public abstract class ProductServiceByFactoryMethod
{
public void Display()
{
IProduct product = CreateProduct();
Console.WriteLine(product.ToString());
}
public abstract IProduct CreateProduct();
}
public class FooService : ProductServiceByFactoryMethod
{
public override IProduct CreateProduct()
{
return new Foo();
}
}
public class BarService : ProductServiceByFactoryMethod
{
public override IProduct CreateProduct()
{
return new Bar();
}
}
/*
* Abstrac Factory 패턴: 구성(Composition)기반
*/
public interface IProductFactory
{
IProduct Create();
}
public class FooFactory: IProductFactory
{
public IProduct Create()
{
return new Foo();
}
}
public class BarFactory: IProductFactory
{
public IProduct Create()
{
return new Bar();
}
}
public class ProductServiceByAbstractFactory
{
public ProductServiceByAbstractFactory(IProductFactory factory)
{
if(factory == null)
throw new ArgumentNullException(nameof(factory));
Factory = factory;
}
public IProductFactory Factory { get; }
public void Display()
{
IProduct product = Factory.Create();
Console.WriteLine(product.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment