• C#委托实现工厂规则注入


    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]
    };
    };
    }
    }

  • 相关阅读:
    [LeetCode] 85. 最大矩形
    [LeetCode] 84. 柱状图中最大的矩形
    [LeetCode] 83. 删除排序链表中的重复元素
    [LeetCode] 81. 搜索旋转排序数组 II
    [LeetCode] 82. 删除排序链表中的重复元素 II
    [LeetCode] 80. 删除排序数组中的重复项 II
    [LeetCode] 79. 单词搜索
    [LeetCode] 77. 组合
    转:快乐Node码农的十个习惯
    转:zookeeper3.4.5安装笔记
  • 原文地址:https://www.cnblogs.com/sulong/p/4917593.html
Copyright © 2020-2023  润新知