Design patterns. Builder. Agent007 Builder
From AsIsWiki
Agent007 Builder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | public class Main { public static void main(String[] args) { Agent007.Builder agentBuilder = new Agent007.Builder( 188 , 90 ); agentBuilder.setIntelligence( 8 ).setCharisma( 7 ).setArmour( 5 ).setLifes( 3 ); Agent007 seanConnery = agentBuilder.build(); agentBuilder.setIntelligence( 7 ).setCharisma( 8 ).setArmour( 3 ).setLifes( 3 ); Agent007 pierceBrosnan = agentBuilder.build(); System.out.println(seanConnery.toString()); System.out.println(pierceBrosnan.toString()); } } class Agent007 { private final int height; // рост private final int weight; // вес private final int intelligence; // интеллект private final int charisma; // харизма private final int armour; // броня private final int lifes; // кол-во жизней public static class Builder { // Обязательные параметры private final int height; private final int weight; // Дополнительные параметры private int intelligence = 1 ; private int charisma = 1 ; private int lifes = 1 ; private int armour = 1 ; public Builder( int height, int weight) { this .height = height; this .weight = weight; } public Builder setIntelligence( int val) { intelligence = val; return this ; } public Builder setCharisma( int val) { charisma = val; return this ; } public Builder setLifes( int val) { lifes = val; return this ; } public Builder setArmour( int val) { armour = val; return this ; } public Agent007 build() { return new Agent007( this ); } } private Agent007(Builder builder) { height = builder.height; weight = builder.weight; intelligence = builder.intelligence; charisma = builder.charisma; armour = builder.armour; lifes = builder.lifes; } @Override public String toString() { return "Agent007{" + "height=" + height + ", weight=" + weight + ", intelligence=" + intelligence + ", charisma=" + charisma + ", armour=" + armour + ", lifes=" + lifes + '}' ; } } |