应用场景:
不同的条件下,不同的逻辑处理。例如:自动挡与手动挡的挂档方式。
UML图
实例代码:
public interface ICar { string GuaDang(); }
public class ShouDong:ICar { public string GuaDang() { return "我是手动挡"; } }
public class ZiDong:ICar { public string GuaDang() { return "我是自动挡"; } }
public class CarFactory { public static ICar GetCar(string type) { switch (type) { case "SD": return new ShouDong(); case "ZD": return new ZiDong(); default: return new ShouDong(); } } }
class Program { static void Main(string[] args) { Console.WriteLine(CarFactory.GetCar("SD").GuaDang()); Console.WriteLine(CarFactory.GetCar("ZD").GuaDang()); } }