티스토리 뷰
목차
반응형
[C# 디자인 패턴] 팩토리 메소드 패턴 예제 (Factory Pattern)
컨셉 요약 - 책 유통 업체가 전국으로 배송하기 위해 3개의 대리점을 개설.
[C# 디자인패턴] 팩토리 메소드패턴
제품을 전달하는 BookStore 클래는 동부, 중부, 서부의 ShipBook() 함수를 몰라도 상관없습니다. BookStore.IDistributor이란 코드를 이용하면 되기 때문이죠. 실제론 아래처럼 사용할 수 있습니다.
1 2 3 | IDistributor b = bookStore.GetDistributor(); //the client gets the distributor without having //to know which distributor is being used |
좀 더, 깊숙이 들어가면 아래처럼 UML이 변경됩니다. BookStore가 두 개라면 말이죠.
[C# 디자인패턴] 팩토리 메소드패턴
이럴 경우엔 위의 코드를 조금 수정해 줍니다.
1 2 3 4 5 6 7 | //this client code will not need to be changed even //if the logic for the distributor changed public void ShipBook(IBookStore s) { IDistributor d = s.GetDistributor(); d.ShipBook(); } |
요약하자면 이런 형태가 되는 것이죠.
[C# 디자인패턴] 팩토리 메소드패턴
아래는 전체 코드입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | public enum CustomerLocation { EastCoast, MidWest, WestCoast } class Program { static void Main(string[] args) { Console.WriteLine("East Coast Customer:"); IBookStore bookstore = new BookStoreA(CustomerLocation.EastCoast); ShipBook(bookstore); Console.WriteLine("Mid West Customer:"); bookstore = new BookStoreA(CustomerLocation.MidWest); ShipBook(bookstore); Console.WriteLine("West Coast Customer:"); bookstore = new BookStoreA(CustomerLocation.WestCoast); ShipBook(bookstore); } //**** client code does not need to be changed *** private static void ShipBook(IBookStore s) { IDistributor d = s.GetDistributor(); d.ShipBook(); } } //the factory public interface IBookStore { IDistributor GetDistributor(); } //concrete factory public class BookStoreA : IBookStore { private CustomerLocation location; public BookStoreA(CustomerLocation location) { this.location = location; } IDistributor IBookStore.GetDistributor() { //internal logic on which distributor to return //*** logic can be changed without changing the client code **** switch (location) { case CustomerLocation.EastCoast: return new EastCoastDistributor(); case CustomerLocation.MidWest: return new MidWestDistributor(); case CustomerLocation.WestCoast: return new WestCoastDistributor(); } return null; } } //the product public interface IDistributor { void ShipBook(); } //concrete product public class EastCoastDistributor : IDistributor { void IDistributor.ShipBook() { Console.WriteLine("Book shipped by East Coast Distributor"); } } //concrete product public class MidWestDistributor : IDistributor { void IDistributor.ShipBook() { Console.WriteLine("Book shipped by Mid West Distributor"); } } //conceret product public class WestCoastDistributor : IDistributor { void IDistributor.ShipBook() { Console.WriteLine("Book shipped by West Coast Distributor"); } } | cs |
[C# 디자인패턴] 팩토리 메소드패턴
[C# 디자인 패턴] 팩토리 메소드 패턴 예제 (Factory Pattern)
반응형