精华内容
下载资源
问答
  • Design Pattern - Builder(C#)

    万次阅读 多人点赞 2019-01-23 20:24:55
    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!... Definition Separate the construction of a complex object from its representation so that the same ...

    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net 

    Definition

    Separate the construction of a complex object from its representation so that the same construction process can create different representations.

    Participants

        The classes and/or objects participating in this pattern are:

    • Builder (VehicleBuilder)
      • Specifies an abstract interface for creating parts of a Product object
    • ConcreteBuilder (MotorCycleBuilder, CarBuilder, ScooterBuilder)
      • Constructs and assembles parts of the product by implementing the Builder interface
      • Defines and keeps track of the representation it creates
      • Provides an interface for retrieving the product
    • Director (Shop)
      • Constructs an object using the Builder interface
    • Product (Vehicle)
      • Represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled
      • Includes classes that define the constituent parts, including interfaces for assembling the parts into the final result

    Sample code in C#


    This structural code demonstrates the Builder pattern in which complex objects are created in a step-by-step fashion. The construction process can create different object representations and provides a high level of control over the assembly of the objects.

    // --------------------------------------------------------------------------------------------------------------------
    // <copyright company="Chimomo's Company" file="Program.cs">
    // Respect the work.
    // </copyright>
    // <summary>
    // Structural Builder Design Pattern.
    // </summary>
    // --------------------------------------------------------------------------------------------------------------------
    namespace CSharpLearning
    {
        using System;
        using System.Collections.Generic;
    
        /// <summary>
        /// Startup class for Structural Builder Design Pattern.
        /// </summary>
        public static class MainApp
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Entry point into console application.
            /// </summary>
            public static void Main()
            {
                // Create director and builders
                var director = new Director();
                Builder b1 = new ConcreteBuilder1();
                Builder b2 = new ConcreteBuilder2();
    
                // Construct two products
                director.Construct(b1);
                Product p1 = b1.GetResult();
                p1.Show();
                director.Construct(b2);
                Product p2 = b2.GetResult();
                p2.Show();
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Director' class
        /// </summary>
        internal class Director
        {
            // Builder uses a complex series of steps
            #region Public Methods and Operators
    
            /// <summary>
            /// The construct.
            /// </summary>
            /// <param name="builder">
            /// The builder.
            /// </param>
            public void Construct(Builder builder)
            {
                builder.BuildPartA();
                builder.BuildPartB();
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Builder' abstract class
        /// </summary>
        internal abstract class Builder
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// The build part a.
            /// </summary>
            public abstract void BuildPartA();
    
            /// <summary>
            /// The build part b.
            /// </summary>
            public abstract void BuildPartB();
    
            /// <summary>
            /// The get result.
            /// </summary>
            /// <returns>
            /// The <see cref="Product"/>.
            /// </returns>
            public abstract Product GetResult();
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteBuilder1' class
        /// </summary>
        internal class ConcreteBuilder1 : Builder
        {
            #region Fields
    
            /// <summary>
            /// The product.
            /// </summary>
            private Product product = new Product();
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The build part a.
            /// </summary>
            public override void BuildPartA()
            {
                this.product.Add("PartA");
            }
    
            /// <summary>
            /// The build part b.
            /// </summary>
            public override void BuildPartB()
            {
                this.product.Add("PartB");
            }
    
            /// <summary>
            /// The get result.
            /// </summary>
            /// <returns>
            /// The <see cref="Product"/>.
            /// </returns>
            public override Product GetResult()
            {
                return this.product;
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteBuilder2' class
        /// </summary>
        internal class ConcreteBuilder2 : Builder
        {
            #region Fields
    
            /// <summary>
            /// The product.
            /// </summary>
            private Product product = new Product();
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The build part a.
            /// </summary>
            public override void BuildPartA()
            {
                this.product.Add("PartX");
            }
    
            /// <summary>
            /// The build part b.
            /// </summary>
            public override void BuildPartB()
            {
                this.product.Add("PartY");
            }
    
            /// <summary>
            /// The get result.
            /// </summary>
            /// <returns>
            /// The <see cref="Product"/>.
            /// </returns>
            public override Product GetResult()
            {
                return this.product;
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Product' class
        /// </summary>
        internal class Product
        {
            #region Fields
    
            /// <summary>
            /// The _parts.
            /// </summary>
            private List<string> parts = new List<string>();
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The add.
            /// </summary>
            /// <param name="part">
            /// The part.
            /// </param>
            public void Add(string part)
            {
                this.parts.Add(part);
            }
    
            /// <summary>
            /// The show.
            /// </summary>
            public void Show()
            {
                Console.WriteLine("\nProduct Parts -------");
                foreach (string part in this.parts)
                {
                    Console.WriteLine(part);
                }
            }
    
            #endregion
        }
    }
    
    // Output:
    /*
    
    Product Parts -------
    PartA
    PartB
    
    Product Parts -------
    PartX
    PartY
    */

    This real-world code demonstates the Builder pattern in which different vehicles are assembled in a step-by-step fashion. The Shop uses VehicleBuilders to construct a variety of Vehicles in a series of sequential steps.

    // --------------------------------------------------------------------------------------------------------------------
    // <copyright company="Chimomo's Company" file="Program.cs">
    // Respect the work.
    // </copyright>
    // <summary>
    // Real-World Builder Design Pattern.
    // </summary>
    // --------------------------------------------------------------------------------------------------------------------
    namespace CSharpLearning
    {
        using System;
        using System.Collections.Generic;
    
        /// <summary>
        /// Startup class for Real-World Builder Design Pattern.
        /// </summary>
        public static class MainApp
        {
            #region Public Methods and Operators
    
            /// <summary>
            /// Entry point into console application.
            /// </summary>
            public static void Main()
            {
                VehicleBuilder builder;
    
                // Create shop with vehicle builders
                var shop = new Shop();
    
                // Construct and display vehicles
                builder = new ScooterBuilder();
                shop.Construct(builder);
                builder.Vehicle.Show();
    
                builder = new CarBuilder();
                shop.Construct(builder);
                builder.Vehicle.Show();
    
                builder = new MotorCycleBuilder();
                shop.Construct(builder);
                builder.Vehicle.Show();
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Director' class
        /// </summary>
        internal class Shop
        {
            // Builder uses a complex series of steps
            #region Public Methods and Operators
    
            /// <summary>
            /// The construct.
            /// </summary>
            /// <param name="vehicleBuilder">
            /// The vehicle builder.
            /// </param>
            public void Construct(VehicleBuilder vehicleBuilder)
            {
                vehicleBuilder.BuildFrame();
                vehicleBuilder.BuildEngine();
                vehicleBuilder.BuildWheels();
                vehicleBuilder.BuildDoors();
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Builder' abstract class
        /// </summary>
        internal abstract class VehicleBuilder
        {
            #region Fields
    
            /// <summary>
            /// The vehicle.
            /// </summary>
            protected Vehicle VehicleField;
    
            #endregion
    
            // Gets vehicle instance
            #region Public Properties
    
            /// <summary>
            /// Gets the vehicle.
            /// </summary>
            public Vehicle Vehicle
            {
                get
                {
                    return this.VehicleField;
                }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The build doors.
            /// </summary>
            public abstract void BuildDoors();
    
            /// <summary>
            /// The build engine.
            /// </summary>
            public abstract void BuildEngine();
    
            /// <summary>
            /// The build frame.
            /// </summary>
            public abstract void BuildFrame();
    
            /// <summary>
            /// The build wheels.
            /// </summary>
            public abstract void BuildWheels();
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteBuilder1' class
        /// </summary>
        internal class MotorCycleBuilder : VehicleBuilder
        {
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="MotorCycleBuilder"/> class.
            /// </summary>
            public MotorCycleBuilder()
            {
                this.VehicleField = new Vehicle("MotorCycle");
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The build doors.
            /// </summary>
            public override void BuildDoors()
            {
                this.VehicleField["doors"] = "0";
            }
    
            /// <summary>
            /// The build engine.
            /// </summary>
            public override void BuildEngine()
            {
                this.VehicleField["engine"] = "500 cc";
            }
    
            /// <summary>
            /// The build frame.
            /// </summary>
            public override void BuildFrame()
            {
                this.VehicleField["frame"] = "MotorCycle Frame";
            }
    
            /// <summary>
            /// The build wheels.
            /// </summary>
            public override void BuildWheels()
            {
                this.VehicleField["wheels"] = "2";
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteBuilder2' class
        /// </summary>
        internal class CarBuilder : VehicleBuilder
        {
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="CarBuilder"/> class.
            /// </summary>
            public CarBuilder()
            {
                this.VehicleField = new Vehicle("Car");
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The build doors.
            /// </summary>
            public override void BuildDoors()
            {
                this.VehicleField["doors"] = "4";
            }
    
            /// <summary>
            /// The build engine.
            /// </summary>
            public override void BuildEngine()
            {
                this.VehicleField["engine"] = "2500 cc";
            }
    
            /// <summary>
            /// The build frame.
            /// </summary>
            public override void BuildFrame()
            {
                this.VehicleField["frame"] = "Car Frame";
            }
    
            /// <summary>
            /// The build wheels.
            /// </summary>
            public override void BuildWheels()
            {
                this.VehicleField["wheels"] = "4";
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'ConcreteBuilder3' class
        /// </summary>
        internal class ScooterBuilder : VehicleBuilder
        {
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="ScooterBuilder"/> class.
            /// </summary>
            public ScooterBuilder()
            {
                this.VehicleField = new Vehicle("Scooter");
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The build doors.
            /// </summary>
            public override void BuildDoors()
            {
                this.VehicleField["doors"] = "0";
            }
    
            /// <summary>
            /// The build engine.
            /// </summary>
            public override void BuildEngine()
            {
                this.VehicleField["engine"] = "50 cc";
            }
    
            /// <summary>
            /// The build frame.
            /// </summary>
            public override void BuildFrame()
            {
                this.VehicleField["frame"] = "Scooter Frame";
            }
    
            /// <summary>
            /// The build wheels.
            /// </summary>
            public override void BuildWheels()
            {
                this.VehicleField["wheels"] = "2";
            }
    
            #endregion
        }
    
        /// <summary>
        /// The 'Product' class
        /// </summary>
        internal class Vehicle
        {
            #region Fields
    
            /// <summary>
            /// The parts.
            /// </summary>
            private Dictionary<string, string> parts = new Dictionary<string, string>();
    
            /// <summary>
            /// The vehicle type.
            /// </summary>
            private string vehicleType;
    
            #endregion
    
            // Constructor
            #region Constructors and Destructors
    
            /// <summary>
            /// Initializes a new instance of the <see cref="Vehicle"/> class.
            /// </summary>
            /// <param name="vehicleType">
            /// The vehicle type.
            /// </param>
            public Vehicle(string vehicleType)
            {
                this.vehicleType = vehicleType;
            }
    
            #endregion
    
            // Indexer
            #region Public Indexers
    
            /// <summary>
            /// The this.
            /// </summary>
            /// <param name="key">
            /// The key.
            /// </param>
            /// <returns>
            /// The <see cref="string"/>.
            /// </returns>
            public string this[string key]
            {
                get
                {
                    return this.parts[key];
                }
    
                set
                {
                    this.parts[key] = value;
                }
            }
    
            #endregion
    
            #region Public Methods and Operators
    
            /// <summary>
            /// The show.
            /// </summary>
            public void Show()
            {
                Console.WriteLine("\n---------------------------");
                Console.WriteLine(" Vehicle Type: {0}", this.vehicleType);
                Console.WriteLine(" Frame : {0}", this.parts["frame"]);
                Console.WriteLine(" Engine : {0}", this.parts["engine"]);
                Console.WriteLine(" #Wheels: {0}", this.parts["wheels"]);
                Console.WriteLine(" #Doors : {0}", this.parts["doors"]);
            }
    
            #endregion
        }
    }
    
    // Output:
    /*
    
    ---------------------------
     Vehicle Type: Scooter
     Frame : Scooter Frame
     Engine : 50 cc
     #Wheels: 2
     #Doors : 0
    
    ---------------------------
     Vehicle Type: Car
     Frame : Car Frame
     Engine : 2500 cc
     #Wheels: 4
     #Doors : 4
    
    ---------------------------
     Vehicle Type: MotorCycle
     Frame : MotorCycle Frame
     Engine : 500 cc
     #Wheels: 2
     #Doors : 0
    */
    展开全文
  • Kotlin Builder模式

    2018-11-21 16:46:22
    class Person(var name: String, var age: Int) { ... constructor(builder: Builder) : this(builder.name, builder.age) companion object { fun builder(): Builder { return Builder...
    class Person(var name: String, var age: Int) {
    
        constructor(builder: Builder) : this(builder.name, builder.age) 
    
        companion object {
            fun builder(): Builder {
                return Builder()
            }
        }
    
        class Builder {
            var name: String = ""
            var age: Int = 0
    
            fun setName(name: String): Builder {
                this.name = name
                return this
            }
    
            fun setAge(age: Int): Builder {
                this.age = age
                return this
            }
    
            fun build(): Person {
                return Person(this)
            }
        }
    }
    

    进阶版(推荐)

    class Person(var name: String, var age: Int) {
    
        constructor(builder: Builder) : this(builder.name, builder.age)
    
        companion object {
            inline fun build(block: Builder.() -> Unit): Person {
                return Builder().apply(block).build()
            }
        }
    
        class Builder {
            var name: String = ""
            var age: Int = 0
    
            fun build(): Person {
                return Person(this)
            }
        }
    }
    

    调用:

    	var p1 = Person.build {
                name = ""
                age = 10
            }
    
    展开全文
  • @Builder

    千次阅读 2019-06-10 14:38:51
    https://www.projectlombok.org/features/Builder...@Builder ... and Bob's your uncle: No-hassle fancy-pants APIs for object creation! @Builderwas introduced as experimental feature in lombok v0.12.0. ...

    https://www.projectlombok.org/features/Builder

    @Builder

    ... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!

    @Builder was introduced as experimental feature in lombok v0.12.0.

    @Builder gained @Singular support and was promoted to the main lombok package since lombok v1.16.0.

    @Builder with @Singular adds a clear method since lombok v1.16.8.

    @Builder.Default functionality was added in lombok v1.16.16.

    @Builder(builderMethodName = "") is legal (and will suppress generation of the builder method) starting with lombok v1.18.8.

    @Builder(access = AccessLevel.PACKAGE) is legal (and will generate the builder class, the builder method, etc with the indicated access level) starting with lombok v1.18.8.

    Overview

    The @Builder annotation produces complex builder APIs for your classes.

    @Builder lets you automatically produce the code required to have your class be instantiable with code such as:
    Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();

    @Builder can be placed on a class, or on a constructor, or on a method. While the "on a class" and "on a constructor" mode are the most common use-case, @Builder is most easily explained with the "method" use-case.

    A method annotated with @Builder (from now on called the target) causes the following 7 things to be generated:

    • An inner static class named FooBuilder, with the same type arguments as the static method (called the builder).
    • In the builder: One private non-static non-final field for each parameter of the target.
    • In the builder: A package private no-args empty constructor.
    • In the builder: A 'setter'-like method for each parameter of the target: It has the same type as that parameter and the same name. It returns the builder itself, so that the setter calls can be chained, as in the above example.
    • In the builder: A build() method which calls the method, passing in each field. It returns the same type that the target returns.
    • In the builder: A sensible toString() implementation.
    • In the class containing the target: A builder() method, which creates a new instance of the builder.

    Each listed generated element will be silently skipped if that element already exists (disregarding parameter counts and looking only at names). This includes the builder itself: If that class already exists, lombok will simply start injecting fields and methods inside this already existing class, unless of course the fields / methods to be injected already exist. You may not put any other method (or constructor) generating lombok annotation on a builder class though; for example, you can not put @EqualsAndHashCode on the builder class.

     

    @Builder can generate so-called 'singular' methods for collection parameters/fields. These take 1 element instead of an entire list, and add the element to the list. For example: Person.builder().job("Mythbusters").job("Unchained Reaction").build(); would result in the List<String> jobs field to have 2 strings in it. To get this behaviour, the field/parameter needs to be annotated with @Singular. The feature has its own documentation.

    Now that the "method" mode is clear, putting a @Builder annotation on a constructor functions similarly; effectively, constructors are just static methods that have a special syntax to invoke them: Their 'return type' is the class they construct, and their type parameters are the same as the type parameters of the class itself.

    Finally, applying @Builder to a class is as if you added @AllArgsConstructor(access = AccessLevel.PACKAGE) to the class and applied the @Builder annotation to this all-args-constructor. This only works if you haven't written any explicit constructors yourself. If you do have an explicit constructor, put the @Builder annotation on the constructor instead of on the class.

    If using @Builder to generate builders to produce instances of your own class (this is always the case unless adding @Builder to a method that doesn't return your own type), you can use @Builder(toBuilder = true) to also generate an instance method in your class called toBuilder(); it creates a new builder that starts out with all the values of this instance. You can put the @Builder.ObtainVia annotation on the parameters (in case of a constructor or method) or fields (in case of @Builder on a type) to indicate alternative means by which the value for that field/parameter is obtained from this instance. For example, you can specify a method to be invoked: @Builder.ObtainVia(method = "calculateFoo").

    The name of the builder class is FoobarBuilder, where Foobar is the simplified, title-cased form of the return type of the target - that is, the name of your type for @Builder on constructors and types, and the name of the return type for @Builder on methods. For example, if @Builder is applied to a class named com.yoyodyne.FancyList<T>, then the builder name will be FancyListBuilder<T>. If @Builder is applied to a method that returns void, the builder will be named VoidBuilder.

    The configurable aspects of builder are:

    • The builder's class name (default: return type + 'Builder')
    • The build() method's name (default: "build")
    • The builder() method's name (default: "builder")
    • If you want toBuilder() (default: no)
    • The access level of all generated elements (default: public).

    Example usage where all options are changed from their defaults:
    @Builder(builderClassName = "HelloWorldBuilder", buildMethodName = "execute", builderMethodName = "helloWorld", toBuilder = true, access = AccessLevel.PRIVATE)

     

    @Builder.Default

    If a certain field/parameter is never set during a build session, then it always gets 0 / null / false. If you've put @Builder on a class (and not a method or constructor) you can instead specify the default directly on the field, and annotate the field with @Builder.Default:
    @Builder.Default private final long created = System.currentTimeMillis();

    @Singular

    By annotating one of the parameters (if annotating a method or constructor with @Builder) or fields (if annotating a class with @Builder) with the @Singular annotation, lombok will treat that builder node as a collection, and it generates 2 'adder' methods instead of a 'setter' method. One which adds a single element to the collection, and one which adds all elements of another collection to the collection. No setter to just set the collection (replacing whatever was already added) will be generated. A 'clear' method is also generated. These 'singular' builders are very complicated in order to guarantee the following properties:

    • When invoking build(), the produced collection will be immutable.
    • Calling one of the 'adder' methods, or the 'clear' method, after invoking build() does not modify any already generated objects, and, if build() is later called again, another collection with all the elements added since the creation of the builder is generated.
    • The produced collection will be compacted to the smallest feasible format while remaining efficient.

     

    @Singular can only be applied to collection types known to lombok. Currently, the supported types are:

    • java.util:
      • IterableCollection, and List (backed by a compacted unmodifiable ArrayList in the general case).
      • SetSortedSet, and NavigableSet (backed by a smartly sized unmodifiable HashSet or TreeSet in the general case).
      • MapSortedMap, and NavigableMap (backed by a smartly sized unmodifiable HashMap or TreeMap in the general case).
    • Guava's com.google.common.collect:
      • ImmutableCollection and ImmutableList (backed by the builder feature of ImmutableList).
      • ImmutableSet and ImmutableSortedSet (backed by the builder feature of those types).
      • ImmutableMapImmutableBiMap, and ImmutableSortedMap (backed by the builder feature of those types).
      • ImmutableTable (backed by the builder feature of ImmutableTable).

     

    If your identifiers are written in common english, lombok assumes that the name of any collection with @Singular on it is an english plural and will attempt to automatically singularize that name. If this is possible, the add-one method will use this name. For example, if your collection is called statuses, then the add-one method will automatically be called status. You can also specify the singular form of your identifier explictly by passing the singular form as argument to the annotation like so: @Singular("axis") List<Line> axes;.
    If lombok cannot singularize your identifier, or it is ambiguous, lombok will generate an error and force you to explicitly specify the singular name.

    The snippet below does not show what lombok generates for a @Singular field/parameter because it is rather complicated. You can view a snippet here.

    With Jackson

    You can customize parts of your builder, for example adding another method to the builder class, or annotating a method in the builder class, by making the builder class yourself. Lombok will generate everything that you do not manually add, and put it into this builder class. For example, if you are trying to configure jackson to use a specific subtype for a collection, you can write something like:

    @Value @Builder
    @JsonDeserialize(builder = JacksonExample.JacksonExampleBuilder.class)
    public class JacksonExample {
    	@Singular private List<Foo> foos;
    	
    	@JsonPOJOBuilder(withPrefix = "")
    	public static class JacksonExampleBuilder implements JacksonExampleBuilderMeta {
    	}
    	
    	private interface JacksonExampleBuilderMeta {
    		@JsonDeserialize(contentAs = FooImpl.class) JacksonExampleBuilder foos(List<? extends Foo> foos)
    	}
    }
    

     

    With Lombok

    import lombok.Builder;
    import lombok.Singular;
    import java.util.Set;

    @Builder
    public class BuilderExample {
      @Builder.Default private long created = System.currentTimeMillis();
      private String name;
      private int age;
      @Singular private Set<String> occupations;
    }

    Vanilla Java

    import java.util.Set;

    public class BuilderExample {
      private long created;
      private String name;
      private int age;
      private Set<String> occupations;
      
      BuilderExample(String name, int age, Set<String> occupations) {
        this.name = name;
        this.age = age;
        this.occupations = occupations;
      }
      
      private static long $default$created() {
        return System.currentTimeMillis();
      }
      
      public static BuilderExampleBuilder builder() {
        return new BuilderExampleBuilder();
      }
      
      public static class BuilderExampleBuilder {
        private long created;
        private boolean created$set;
        private String name;
        private int age;
        private java.util.ArrayList<String> occupations;
        
        BuilderExampleBuilder() {
        }
        
        public BuilderExampleBuilder created(long created) {
          this.created = created;
          this.created$set = true;
          return this;
        }
        
        public BuilderExampleBuilder name(String name) {
          this.name = name;
          return this;
        }
        
        public BuilderExampleBuilder age(int age) {
          this.age = age;
          return this;
        }
        
        public BuilderExampleBuilder occupation(String occupation) {
          if (this.occupations == null) {
            this.occupations = new java.util.ArrayList<String>();
          }
          
          this.occupations.add(occupation);
          return this;
        }
        
        public BuilderExampleBuilder occupations(Collection<? extends String> occupations) {
          if (this.occupations == null) {
            this.occupations = new java.util.ArrayList<String>();
          }

          this.occupations.addAll(occupations);
          return this;
        }
        
        public BuilderExampleBuilder clearOccupations() {
          if (this.occupations != null) {
            this.occupations.clear();
          }
          
          return this;
        }

        public BuilderExample build() {
          // complicated switch statement to produce a compact properly sized immutable set omitted.
          Set<String> occupations = ...;
          return new BuilderExample(created$set ? created : BuilderExample.$default$created(), name, age, occupations);
        }
        
        @java.lang.Override
        public String toString() {
          return "BuilderExample.BuilderExampleBuilder(created = " this.created + ", name = " this.name + ", age = " this.age + ", occupations = " this.occupations + ")";
        }
      }
    }

    Supported configuration keys:

    lombok.builder.flagUsage = [warning | error] (default: not set)

    Lombok will flag any usage of @Builder as a warning or error if configured.

    lombok.singular.useGuava = [true | false] (default: false)

    If true, lombok will use guava's ImmutableXxx builders and types to implement java.util collection interfaces, instead of creating implementations based on Collections.unmodifiableXxx. You must ensure that guava is actually available on the classpath and buildpath if you use this setting. Guava is used automatically if your field/parameter has one of the guava ImmutableXxx types.

    lombok.singular.auto = [true | false] (default: true)

    If true (which is the default), lombok automatically tries to singularize your identifier name by assuming that it is a common english plural. If false, you must always explicitly specify the singular name, and lombok will generate an error if you don't (useful if you write your code in a language other than english).

    Small print

    @Singular support for java.util.NavigableMap/Set only works if you are compiling with JDK1.8 or higher.

    You cannot manually provide some or all parts of a @Singular node; the code lombok generates is too complex for this. If you want to manually control (part of) the builder code associated with some field or parameter, don't use @Singular and add everything you need manually.

    The sorted collections (java.util: SortedSetNavigableSetSortedMapNavigableMap and guava: ImmutableSortedSetImmutableSortedMap) require that the type argument of the collection has natural order (implements java.util.Comparable). There is no way to pass an explicit Comparator to use in the builder.

    An ArrayList is used to store added elements as call methods of a @Singular marked field, if the target collection is from the java.util package, even if the collection is a set or map. Because lombok ensures that generated collections are compacted, a new backing instance of a set or map must be constructed anyway, and storing the data as an ArrayList during the build process is more efficient that storing it as a map or set. This behaviour is not externally visible, an implementation detail of the current implementation of the java.util recipes for @Singular @Builder.

    With toBuilder = true applied to methods, any type parameter of the annotated method itself must also show up in the return type.

    The initializer on a @Builder.Default field is removed and stored in a static method, in order to guarantee that this initializer won't be executed at all if a value is specified in the build. This does mean the initializer cannot refer to thissuper or any non-static member. If lombok generates a constructor for you, it'll also initialize this field with the initializer.

    Various well known annotations about nullity cause null checks to be inserted and will be copied to parameter of the builder's 'setter' method. See Getter/Setter documentation's small print for more information.

    You can suppress the generation of the builder() method, for example because you just want the toBuilder()functionality, by using: @Builder(builderMethodName = ""). Any warnings about missing @Builder.Defaultannotations will disappear when you do this, as such warnings are not relevant when only using toBuilder() to make builder instances.

    You can use @Builder for copy constructors: foo.toBuilder().build() makes a shallow clone. Consider suppressing the generating of the builder method if you just want this functionality, by using: @Builder(toBuilder = true, builderMethodName = "").

    Due to a peculiar way javac processes static imports, trying to do a non-star static import of the static builder()method won't work. Either use a star static import: `import static TypeThatHasABuilder.*;` or don't statically import the builder method.

    If setting the access level to PROTECTED, all methods generated inside the builder class are actually generated as public; the meaning of the protected keyword is different inside the inner class, and the precise behaviour that PROTECTED would indicate (access by any source in the same package is allowed, as well as any subclasses from the outer class, marked with @Builder is not possible, and marking the inner members public is as close as we can get.

    展开全文
  • CocosBuilder3.0

    千次下载 热门讨论 2013-01-31 13:32:52
    CocosBuilder 已经被Zynga 使用在游戏Dream PetHouse 和 Zynga Slots开发中
  • ![图片说明](https://img-ask.csdn.net/upload/201807/25/1532479706_20412.jpg) Errors running builder 'Maven Project Builder' on project 'selenium'. java.lang.NullPointerException
  • C++Builder 概述

    千次阅读 2018-11-23 16:30:24
    下面简单介绍一下关于C++builder这款软件的强大功能与基本情况: 1、C++Builder 是一个强大的可视化开发工具,是灵活的 C++语言和随心所欲的可视化开发完美结合的产物。我们可以很方便地在C++builder中设计我们自己...

    下面简单介绍一下关于C++builder这款软件的强大功能与基本情况:

    1、C++Builder 是一个强大的可视化开发工具,是灵活的 C++语言和随心所欲的可视化开发完美结合的产物。我们可以很方便地在C++builder中设计我们自己喜欢的电路或者其它功能模块。

    2、Inprise(原Borland)公司推出的Turbo C、Turbo C++、Borland C++以及Borland C++Builder,无不是 C/C++编程者所钟爱的编程工具,而且每一个都称得上经典之作,Delphi 更是 RAD 开发工具中最受钟爱的编程工具。C++ Builder 中则嵌入了 Delphi 中使用的高效的VCL(Visual Component Library,可视化组件库),使得开发人员不必要在C++高效的底层控制和轻松的VCL 编程环境之间作出选择。因此我们需要了解其基本发展。

    3、下面是安装BCB6 对系统的最低要求:

    1)Intel Pentium II/400 MHz 或兼容产品

    2)Microsoft Windows 98、2000 (SP2)或XP

    3)128 MB RAM (建议256 MB)

    4)750 MB 硬盘空间(完全安装)

    5)CD-ROM 驱动器

    6)SVGA 或更高分辨率显示器(800x600,256 色)

    7)鼠标或其他指示设备

    4、BCB6 的主要特性如下:

    • 通过Web 服务简化企业到企业集成
    • 提高Web 应用开发的功能和速度
    • 构建支持Web 服务的高性能中间件
    • 利用业届标准的优势,支持SOAP、XML、WSDL 和XSL 等协议
    • 为Windows 和Linux 操作系统构建可跨平台运行的应用程序
    • 通过高性能的32 位源代码编译器提高效率                                                                                                                                       • 支持IBM DB2、Informix、Oracle、Sybase、MySQL 、dBASE、Paradox 和BorlandInterBase 等数据库

    总结:可以看出BCB6在Web服务的应用中做了比较多的工作,增添了利用C++进行电子商务的快速开发的功能。

    展开全文
  • bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library? 几经周折才知道是bs4调用了python自带的html解析器,我用的mac,默认安装的...
  • c++builder6和c++builder之间的差异? c++builder6和c++builder之间的差异? c++builder6和c++builder之间的差异? c++builder6和c++builder之间的差异? c++builder6和c++builder之间的差异? c++builder6和c++...
  • Lombok @Builder 不能builder父类问题

    千次阅读 2019-09-03 15:54:06
    今天在使用 Lombok 注解 Builder 的时候遇到一个很坑的问题,Builder 注解不能对父类进行链式调用,具体代码如下 BaseEntityCommon.java @Data @NoArgsConstructor @AllArgsConstructor @MappedSuperclass public ...
  • 在Laravel中出现了两处针对数据库的Builder,一时分不清楚。 Eloquent\Builder Query\Builder 首先,确认Eloquent\Builder与Query\Builder是否是有继承关系: 1/ 打印两者之间的instanceof关系,发现并没有关系...
  • 承接上一篇博客观察者模式,这一期我们一起来了解一下Builder模式。我们最近几期博客打算主要讲一下单例模式、观察者模式、Build模式,目的是为了方便后期为大家带来RXJava+Retrofit2.0+Okhttp3结合使用的网络请求...
  • Builder模式

    千次阅读 2015-07-10 19:03:01
    Builder模式Builder模式要解决的问题是把对象的构建和对象的表示分开来。当对象复杂的时候我,我们可以一步步来构建对象,在每一步的构建过程中,可以引入参数,通过不同的参数,即使经过相同的步骤最后可以得到不同...
  • PowerBuilder2017

    千次阅读 2018-04-27 17:13:27
    PowerBuilder 2017 R2新一代的PowerBuilder保留了您热爱本地PowerBuilder开发的一切,同时使用开放标准和云技术来增强您的项目效率。PowerBuilder 2017 R2将PowerBuilder的高生产力业务应用程序开发功能引入Windows ...
  • 上次干这事已经是一年前了,之前的做法特别的繁琐、冗余,具体就是创建一个自定义 Builder 类,继承自 Query\Builder,然后覆盖 Connection 里面获取 Builder 的方法,返回自定义的 Builder,还有其他一系列很长的...
  • windowbuilder如何使用

    万次阅读 多人点赞 2018-04-27 23:13:19
    eclipse安装好windowbuilder之后(如何安装查看之前的博客)打开eclipse新建一个项目,在该项目上右键如下,选择design等待一会出现这个界面,对其进行操作点击右边红色标记的部分进行相关窗体的设计窗体基本样式...
  • c++builder控件大全

    热门讨论 2012-04-27 16:52:06
    c++builder控件大全.
  • 摘要:目的:开发中喜欢builder模式去构造一个实例,而当一个对象的属性过多的时候,手动的去完成一个类的builder是很繁琐的;所以如果能够自动生成相应的代码在开发中是很有必要的原理:builder模式代码的自动生成借鉴于...
  • WindowBuilder的安装与使用

    万次阅读 多人点赞 2018-03-09 15:21:17
    最近因为学校课程设计的原因,需要大量的使用GUI画界面,但是如果只是单纯的靠写标签的方式,工作量是非常大的... WindowBuilder的安装 1.查看你的Eclipse的版本 在你的eclipse中点击Help-&gt;About Eclipse, ...
  • PowerBuilder 2018

    千次阅读 2018-04-27 17:14:13
    即将到来的PowerBuilder 2018将在原生PowerBuilder IDE中提供新的目标,使开发人员能够在C#中快速创建功能强大的业务逻辑基于Web的中间层。基于DataWindow技术和跨OS .NET Core框架,您将比Visual Studio更快地开发...
  • Errors occurred during the build... Errors running builder 'Integrated External Tool Builder' on project 'xinghe-base'.The builder launch configuration could not be found.The builder launch configuratio
  • JAVA windowbuilder

    2017-06-14 13:30:10
    入门JAVA 我重新更新了eclipse 现在是eclipse neon版本 想下载windowbuilder 但现在官网还没有该版本 请问可以用4.5版(Mars版)代替吗?
  • errors running builder "Integerate External Tool Builder "  解决办法 项目右键-->properties-->builder: 如下图,可以看到几个Invalid External Tool Builder,把他们remove掉重新部署即可
  • 在老的版本中是使用Notification 新的版本是使用Notification.Builder 为了兼容性现在使用NotificationCompat.Builder
  • JavaFX Scene Builder 2.0

    热门讨论 2014-11-27 16:47:46
    适用平台:Windows 32/64 bit 软件格式:.msi ...JavaFX Scene Builder提供一个可视化布局环境,允许你为JavaFX程序快速设计用户界面而无需写任何代码。它允许在JavaFX场景上简单的为用户界面拖拽布局。
  • cocosbuilder入门

    千次阅读 2018-10-16 19:06:26
    cocosbuilder 简介:https://blog.csdn.net/sssssnian/article/details/26450747 cocos2dx 界面自适应解决方案:http://codingnow.cn/cocos2d-x/975.html cocosbuilder 建立简单界面:...
  • 在eclipse构建项目的时候,一直报如下错误: ...Errors running builder "Integrated External Tool Builder" on project project. The builder launch configuration could not be found. Errors running builder...
  • Modelbuilder快速入门

    万次阅读 多人点赞 2016-10-10 08:40:08
    Modelbuilder快速入门 by 李远祥 什么是modelbuilder 模型构建器是一个用来创建、编辑和管理模型的应用程序。模型是将一系列地理处理工具串联在一起的工作流,它将其中一个工具的输出作为另一个工具的输入。也可以...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 108,273
精华内容 43,309
关键字:

builder