zoukankan      html  css  js  c++  java
  • 建造者模式和工厂模式的区别

    它们目的都是创建一个复杂的对象

    工厂模式注重的是整体对象的创建方法,而建造者模式注重的是对象的创建过程,创建对象的过程方法可以在创建时自由调用。

    看一下建造者模式的例子就明白了:

     1 public class EmployeeBuilder
     2 {
     3     private int id = 1;
     4     private string firstname = "first";
     5     private string lastname = "last";
     6     private DateTime birthdate = DateTime.Today;
     7     private string street = "street";
     8 
     9     public Employee Build()
    10     {
    11         return new Employee(id, firstname, lastname, birthdate, street);
    12     }
    13 
    14     public EmployeeBuilder WithFirstName(string firstname)
    15     {
    16         this.firstname = firstname;
    17         return this;
    18     }
    19 
    20     public EmployeeBuilder WithLastName(string lastname)
    21     {
    22         this.lastname = lastname;
    23         return this;
    24     }
    25 
    26     public EmployeeBuilder WithBirthDate(DateTime birthdate)
    27     {
    28         this.birthdate = birthdate;
    29         return this;
    30     }
    31 
    32     public EmployeeBuilder WithStreet(string street)
    33     {
    34         this.street = street;
    35         return this;
    36     }
    37 
    38     public static implicit operator Employee(EmployeeBuilder instance)
    39     {
    40         return instance.Build();
    41     }
    42 }

    调用:

    void main(){
    Employee emp1 = new EmployeeBuilder().WithFirstName("Kenneth")
                                                .WithLastName("Truyers");
    
    Employee emp2 = new EmployeeBuilder().WithBirthDate(new DateTime(1983, 1,1));
    }
  • 相关阅读:
    Tensorflow 2 flower_photos花卉数据集手动下载、离线安装、本地加载、快速读取
    [CC]ccHObject
    [CC]CC插件初探
    [g2o]一个备忘
    [PCL]keypoint
    [PCL]NDT点云匹配方法
    近邻搜索算法
    点云匹配和ICP算法概述
    [PCL]5 ICP算法进行点云匹配
    [PCL]4 PCL中图像匹配的几个类图
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11999850.html
Copyright © 2011-2022 走看看