zoukankan      html  css  js  c++  java
  • 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]
    };
    };
    }
    }

  • 相关阅读:
    大数据方向招人难啊!!
    .netcore 急速接入第三方登录,不看后悔
    T-SQL——函数——时间操作函数
    T-SQL——关于XML类型
    机器学习方法
    可读性友好的JavaScript:两个专家的故事
    快速了解 JavaScript ES2019 的五个新增特性
    了解 Vue 的 Compsition API
    使用 JavaScript 操作浏览器历史记录 API
    JavaScript ES 模块:现代化前端编程必备技能
  • 原文地址:https://www.cnblogs.com/sulong/p/4917593.html
Copyright © 2011-2022 走看看