委托注入
class Program { static void Main(string[] args) { Func<EmployeeFactory.EmployeeparaContent, Employee.EmployeeAddress> employeeAddressPr = (s) => { return new Employee.EmployeeAddress() { Address1 = s.EmployeeAdress.Split(‘,‘)[0], Address2 = s.EmployeeAdress.Split(‘,‘)[1] }; }; var empolyea= EmployeeFactory.CreateEmployee("wzj", "北京1,杭州2", employeeAddressPr); Console.Write(empolyea.Name + "\t" + empolyea.AddressCollers.Address1 + "|" + empolyea.AddressCollers.Address2); Console.ReadLine(); } } //员工类 public partial class Employee { //员工的地址类 public class EmployeeAddress { public string Address1 { set; get; } public string Address2 { set; get; } } //名字 public string Name{set;get;} //员工的地址信息 public EmployeeAddress AddressCollers { set; get; } } //创建员工的简单工厂类 设计模式之创建形态 public class EmployeeFactory { public class EmployeeparaContent { public string EmployeeAdress { set; get; } } //创建员工的方法 地址处理通过动态的委托来处理 可以随时变化处理方式*- public static Employee CreateEmployee(string name, string address, Func<EmployeeFactory.EmployeeparaContent, Employee.EmployeeAddress> adressFactory) { EmployeeparaContent parrcontent = new EmployeeparaContent(); parrcontent.EmployeeAdress = address; //通过委托来代替工厂创建参数类型 更灵活 return new Employee() { Name = name, AddressCollers = adressFactory(parrcontent) }; } }
工厂创建的优势:对象的创建依赖工厂的创建方法 还不是依赖于new 如果这个对象的创建需要修改 new 的地方都需要改 工厂模式的话只需要修改工厂代码就行
2.抽象工厂
用接口吧创建的对象的行为和成员变量给抽象出来
然后创建的的时候根据配置文件或者其他的 来创建继承该接口的对象 这样就符合依赖倒置的原则高层不依赖低层 应该依赖抽象
时间: 2024-10-13 22:33:03