using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//创建型-工厂模式、工厂规则注入、委托工厂
namespace Chap2_2
{
class Program
{
static void Main(string[] args)
{
Func<EmployeeFactory.EmployeeCreateparameterContext, Employee.EmployeeAddress> addressFactory = (context) =>
{
return new Employee.EmployeeAddress()
{
Address1 = context.AddressString.Split('、')[0],
Address2 = context.AddressString.Split('、')[1]
};
};
// Employee emp = EmployeeFactory.CreateEmployee("Plen Wu", "塔希提、塞舌尔", EmployeeFactory.addressFactory1);
Employee emp = EmployeeFactory.CreateEmployee("Plen Wu", "塔希提、塞舌尔", addressFactory);
Console.WriteLine(string.Format("员工名:{0}",emp.Name));
Console.WriteLine(string.Format("户籍地:{0}", emp.AddressCollection.Address1));
Console.WriteLine(string.Format("工作地:{0}", emp.AddressCollection.Address2));
Console.ReadKey();
}
}
public partial class Employee
{
public class EmployeeAddress
{
public string Address1 { get; set; }
public string Address2 { get; set; }
}
public EmployeeAddress AddressCollection { get; set; }
public string Name { get; set; }
}
/// <summary>
/// 工厂规则通过委托注入,可以保持工厂的稳定性
/// </summary>
public class EmployeeFactory
{
/// <summary>
/// 创建地址的上下文类
/// </summary>
public class EmployeeCreateparameterContext
{
public string AddressString { get; set; }
}
public static Employee CreateEmployee(string name, string addressStr, Func<EmployeeFactory.EmployeeCreateparameterContext, Employee.EmployeeAddress> addressFactory)
{
EmployeeCreateparameterContext parameterContext = new EmployeeCreateparameterContext() { AddressString = addressStr };
return new Employee()
{
Name = name,
AddressCollection = addressFactory(parameterContext)
};
}
static public Func<EmployeeFactory.EmployeeCreateparameterContext, Employee.EmployeeAddress> addressFactory1 = (context) =>
{
return new Employee.EmployeeAddress()
{
Address1 = context.AddressString.Split('、')[0],
Address2 = context.AddressString.Split('、')[1]
};
};
}
}