看不见PPT的请自行解决DNS污染问题。
相关类的代码:
1 namespace FactoryPatternConsole.Model 2 { 3 public class Address 4 { 5 public string CountryCode { get; set; } 6 } 7 }
1 namespace FactoryPatternConsole.Model 2 { 3 public class Order 4 { 5 public decimal TotalCost { get; set; } 6 public decimal WeightInKG { get; set; } 7 public string CourierTrackingId { get; set; } 8 public Address DispatchAddress { get; set; } 9 } 10 }
1 namespace FactoryPatternConsole.Model 2 { 3 public interface IShippingCourier 4 { 5 string GenerateConsignmentLabelFor(Address address); 6 } 7 }
1 namespace FactoryPatternConsole.Model 2 { 3 public class DHL : IShippingCourier 4 { 5 public string GenerateConsignmentLabelFor(Address address) 6 { 7 return "DHL-XXXX-XXXX-XXXX"; 8 } 9 } 10 }
1 namespace FactoryPatternConsole.Model 2 { 3 public class RoyalMail:IShippingCourier 4 { 5 public string GenerateConsignmentLabelFor(Address address) 6 { 7 return "RM-XXXX-XXXX-XXXX"; 8 } 9 } 10 }
1 using FactoryPatternConsole.Model; 2 3 namespace FactoryPatternConsole.Factory 4 { 5 public static class UKShippingCourierFactory 6 { 7 public static IShippingCourier CreateShippingCourier(Order order) 8 { 9 if (order.TotalCost > 100 || order.WeightInKG > 5) 10 { 11 return new DHL(); 12 } 13 else 14 { 15 return new RoyalMail(); 16 } 17 } 18 } 19 }
1 using FactoryPatternConsole.Factory; 2 using FactoryPatternConsole.Model; 3 4 namespace FactoryPatternConsole.Service 5 { 6 public class OrderService 7 { 8 public void Dispatch(Order order) 9 { 10 IShippingCourier shippingCourier = UKShippingCourierFactory.CreateShippingCourier(order); 11 12 order.CourierTrackingId = shippingCourier.GenerateConsignmentLabelFor(order.DispatchAddress); 13 } 14 } 15 }
测试用代码:
1 using FactoryPatternConsole.Model; 2 using FactoryPatternConsole.Service; 3 using System; 4 5 namespace FactoryPatternConsole 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 OrderService service = new OrderService(); 12 foreach (Order order in GetOrders()) 13 { 14 service.Dispatch(order); 15 Console.WriteLine(string.Format("TotalCost:{0}, WeightInKG:{1}, CourierTrackingId:{2}", 16 order.TotalCost, order.WeightInKG, order.CourierTrackingId)); 17 } 18 Console.ReadLine(); 19 } 20 21 public static Order[] GetOrders() 22 { 23 return new Order[] { 24 new Order() 25 { 26 TotalCost = 100, 27 WeightInKG = 5, 28 DispatchAddress = new Address() { CountryCode = "CN" }, 29 }, 30 new Order() 31 { 32 TotalCost = 100.1m, 33 WeightInKG = 4, 34 DispatchAddress = new Address() { CountryCode = "CN" }, 35 }, 36 new Order() 37 { 38 TotalCost = 100, 39 WeightInKG = 5.1m, 40 DispatchAddress = new Address() { CountryCode = "CN" }, 41 }, 42 }; 43 } 44 } 45 }
执行结果: