├── Chapter02 ├── Bicycle.java ├── Driver.java ├── TwoWheeled.java └── Vehicle.java ├── Chapter03 ├── CH3ChainResponsibility │ ├── AcademicEmailHandler.java │ ├── AdminEmailHandler.java │ ├── AdvisingEmailHandler.java │ ├── AlumniEmailHandler.java │ ├── FinanceEmailHandler.java │ ├── HREmailHandler.java │ ├── MainEmailHandler.java │ └── UniversityEmailHandler.java ├── CH3Command │ └── ControlBox.java ├── CH3Interpreter │ ├── Conversion.java │ ├── Expression.java │ ├── InterpreterDriver.java │ └── MapIntToCharacters.java ├── CH3Iterator │ └── IteratorExample.java ├── CH3Mediator │ ├── AssemblySystem.java │ ├── EmergencyBreak.java │ ├── Hopper.java │ ├── Starter.java │ ├── SystemAccelerator.java │ └── WidgetProductionSystem.java ├── CH3Memento │ ├── GameMission.java │ └── GameMissionMemento.java ├── CH3NullObject │ ├── EasternTrain.java │ ├── NorthernTrain.java │ ├── NullObjectTrain.java │ ├── SouthernTrain.java │ ├── TrainStatus.java │ └── WesternTrain.java ├── CH3Observer │ ├── ForumMonitor.java │ ├── Observable.java │ ├── Observer.java │ └── StudentDashboard.java └── CH3State │ ├── Driver.java │ ├── Printer.java │ ├── PrinterController.java │ ├── PrinterOffLine.java │ └── PrinterOnLine.java ├── Chapter04 ├── CH4AbstractFactory │ ├── Daughter.java │ ├── Engine.java │ ├── Frame.java │ ├── Grandmother.java │ ├── Kitchen.java │ ├── Mother.java │ ├── MotorHomeAbstractFactory.java │ ├── MotorHomeDriver.java │ ├── Style.java │ ├── Type.java │ ├── TypeAEngine.java │ ├── TypeAFactory.java │ ├── TypeAFrame.java │ ├── TypeAKitchen.java │ ├── TypeAStyle.java │ ├── TypeBEngine.java │ ├── TypeBFactory.java │ ├── TypeBFrame.java │ ├── TypeBKitchen.java │ ├── TypeBStyle.java │ ├── TypeCEngine.java │ ├── TypeCFactory.java │ ├── TypeCFrame.java │ ├── TypeCKitchen.java │ └── TypeCStyle.java ├── CH4Builder │ ├── Builder.java │ ├── CommercialRoaster.java │ ├── PersonalRoaster.java │ ├── Roaster.java │ ├── RoasterDirector.java │ └── RoasterDriver.java ├── CH4Factory │ ├── ConcreteMowerFactory.java │ ├── Mower.java │ ├── MowerDriver.java │ ├── MowerFactory.java │ ├── Push.java │ └── Riding.java ├── CH4Prototype │ ├── BaseLevel.java │ ├── City.java │ ├── Dungeon.java │ ├── Forest.java │ └── LevelDriver.java ├── CH4SimpleFactory │ ├── CommercialLawnMowerSeat.java │ ├── LawnMowerSeat.java │ ├── LawnMowerSeatDriver.java │ ├── LawnMowerSeatFactory.java │ └── ResidentialLawnMowerSeat.java └── CH4Singelton │ ├── AccountDriver.java │ └── CreateBankAccount.java ├── Chapter05 ├── CH5Adapter │ ├── AcreageDeterminator.java │ ├── AcreageDeterminatorAdapter.java │ ├── AdapterDriver.java │ ├── Estate.java │ └── Lot.java ├── CH5Bridge │ ├── Administrator.java │ ├── Adult.java │ ├── Antibiotic.java │ ├── BridgeDriver.java │ ├── Child.java │ ├── Medicine.java │ ├── PainRelief.java │ ├── Patient.java │ ├── Student.java │ ├── Teacher.java │ └── User.java ├── CH5Composite │ ├── Chef.java │ ├── KitchenStaff.java │ └── KitchenStaffDriver.java ├── CH5Decorator │ ├── AbstractDecorator.java │ ├── ConcreteDecorator1.java │ ├── ConcreteDecorator2.java │ ├── ConcretePrinter.java │ ├── DecoratorDriver.java │ └── Printer.java ├── CH5Facade │ ├── FacadeDriver.java │ ├── MealComponents │ │ ├── MealProtein.java │ │ ├── MealStarch.java │ │ └── MealVegetable.java │ └── MealFacade │ │ └── MealFacade.java ├── CH5Flyweight │ ├── Mattress.java │ ├── MattressDriver.java │ ├── MattressFactory.java │ └── MattressInterface.java └── CH5Proxy │ ├── MasterClasses │ ├── ConcreteWeather.java │ └── Weather.java │ └── ProxyClasses │ ├── Proxy.java │ └── ProxyDriver.java ├── Chapter07 └── CH7MVC │ ├── Book.java │ ├── BookController.java │ ├── BookView.java │ └── MVCArchitecturalPattern.java ├── Chapter08 ├── CH8Fibonacci1 │ └── FibonacciTest1.java ├── CH8Fibonacci2 │ └── FibonacciTest2.java ├── CH8Lambda1 │ ├── Driver.java │ └── FunctionalGift.java ├── CH8Lambda2 │ ├── Driver.java │ └── FunctionalGift.java ├── CH8Loan1 │ ├── Driver.java │ └── FileToProcess.java ├── CH8Loan2 │ ├── Driver2.java │ └── FileToProcess2.java ├── CH8Stream │ └── StreamExample.java └── CH8TailCall │ └── TailCallExample.java ├── Chapter09 ├── CH9AsynchronousCommunication │ ├── CallbackListener.java │ ├── CallerOne.java │ └── CallerTwo.java ├── CH9BoundedQueue │ ├── Bounded.java │ └── Driver.java ├── CH9Caching │ ├── CacheDriver.java │ ├── ExampleCache.java │ └── Player.java ├── CH9FailFast │ ├── FailFastImplementation.java │ └── FailFastImplementation2.java ├── CH9FailureHandling │ └── ControlledFailure.java ├── CH9IdempotencyExample │ ├── IdempotencyDriver.java │ └── Patient.java └── CH9Stateless │ ├── Corgi.java │ ├── CorgiAwake.java │ ├── CorgiEat.java │ ├── CorgiPlay.java │ ├── CorgiSit.java │ ├── CorgiSleep.java │ ├── CorgiState.java │ ├── CorgiWalk.java │ └── StatelessDriver.java ├── LICENSE └── README.md /Chapter02/Bicycle.java: -------------------------------------------------------------------------------- 1 | package com.three19; 2 | 3 | public class Bicycle extends TwoWheeled { 4 | 5 | // instance variable declarations 6 | private int gears = 0; 7 | private double cost = 0.0; 8 | private double weight = 0.0; 9 | private String color = ""; 10 | 11 | // constructor - default 12 | Bicycle() { 13 | } 14 | 15 | // constructor - String parameter 16 | Bicycle(String aColor) { 17 | this.color = aColor; 18 | } 19 | 20 | // constructor - int parameter 21 | Bicycle(int nbrOfGears) { 22 | this.gears = nbrOfGears; 23 | } 24 | 25 | // constructor - int, double, double, String parameters 26 | Bicycle(int nbrOfGears, double theCost, double theWeight, String aColor) { 27 | this.gears = nbrOfGears; 28 | this.cost = theCost; 29 | this.weight = theWeight; 30 | this.color = aColor; 31 | } 32 | 33 | // method to output Bicycle's information 34 | public void outputData() { 35 | System.out.println("\nBicycle Details:"); 36 | System.out.println("Gears : " + this.gears); 37 | System.out.println("Cost : " + this.cost); 38 | System.out.println("Weight : " + this.weight + " lbs"); 39 | System.out.println("Color : " + this.color); 40 | } 41 | 42 | // method to output Bicycle's information - overloaded 43 | // - method call chaining enabled 44 | public Bicycle outputData(String bikeText) { 45 | System.out.println("\nBicycle " + bikeText + " Details:"); 46 | System.out.println("Gears : " + this.gears); 47 | System.out.println("Cost : " + this.cost); 48 | System.out.println("Weight : " + this.weight + " lbs"); 49 | System.out.println("Color : " + this.color); 50 | 51 | return this; 52 | } 53 | 54 | // Accessors (Getters) 55 | public int getGears() { 56 | return this.gears; 57 | } 58 | 59 | public double getCost() { 60 | return this.cost; 61 | } 62 | 63 | public double getWeight() { 64 | return this.weight; 65 | } 66 | 67 | public String getColor() { 68 | return this.color; 69 | } 70 | 71 | 72 | // Mutators (Setters) - method call chaining enabled 73 | public Bicycle setGears(int nbr) { 74 | this.gears = nbr; 75 | return this; 76 | } 77 | 78 | public Bicycle setCost(double amt) { 79 | this.cost = amt; 80 | return this; 81 | } 82 | 83 | public Bicycle setWeight(double lbs) { 84 | this.weight = lbs; 85 | return this; 86 | } 87 | 88 | public Bicycle setColor(String theColor) { 89 | this.color = theColor; 90 | return this; 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /Chapter02/Driver.java: -------------------------------------------------------------------------------- 1 | package com.three19; 2 | 3 | public class Driver { 4 | 5 | public static void main(String[] args) { 6 | 7 | // Example calls to mutators 8 | Bicycle myBike = new Bicycle(); 9 | myBike.setGears(24); 10 | myBike.setCost(319.99); 11 | myBike.setWeight(13.5); 12 | myBike.setColor("Purple"); 13 | System.out.println("\nmyBike's color is " + myBike.getColor()); 14 | 15 | 16 | // Example of calls to overloaded constructor 17 | Bicycle myBike1 = new Bicycle(); 18 | Bicycle myBike2 = new Bicycle("Brown"); 19 | Bicycle myBike3 = new Bicycle(22); 20 | Bicycle myBike4 = new Bicycle(22, 319.99, 13.5, "White"); 21 | 22 | myBike1.outputData("Nbr 1"); 23 | myBike2.outputData("Nbr 2"); 24 | myBike3.outputData("Nbr 3"); 25 | myBike4.outputData("Nbr 4"); 26 | 27 | 28 | // Example using method call chaining 29 | Bicycle myBike5 = new Bicycle(24, 418.50, 17.2, "Green"); 30 | myBike5.setColor("Peach").setGears(32).outputData("Number 5"); 31 | 32 | 33 | // "IS A" Checks 34 | System.out.println("\n\"IS A\" CHECKS"); 35 | 36 | // focus on myBike6 37 | Bicycle myBike6 = new Bicycle(); 38 | 39 | if (myBike6 instanceof Bicycle) 40 | System.out.println("myBike6 Instance of Bicycle: True"); 41 | else 42 | System.out.println("myBike6 Instance of Bicycle: False"); 43 | 44 | if (myBike6 instanceof TwoWheeled) 45 | System.out.println("myBike6 Instance of TwoWheeled: True"); 46 | else 47 | System.out.println("myBike6 Instance of TwoWheeled: False"); 48 | 49 | if (myBike6 instanceof Vehicle) 50 | System.out.println("myBike6 Instance of Vehicle: True"); 51 | else 52 | System.out.println("myBike6 Instance of Vehicle: False"); 53 | 54 | if (myBike6 instanceof Object) 55 | System.out.println("myBike6 Instance of Object: True"); 56 | else 57 | System.out.println("myBike6 Instance of Object: False"); 58 | 59 | // focus on TwoWheeled 60 | TwoWheeled myTwoWheeled = new TwoWheeled(); 61 | 62 | if (myTwoWheeled instanceof Bicycle) 63 | System.out.println("\nmyTwoWheeled Instance of Bicycle: True"); 64 | else 65 | System.out.println("\nmyTwoWheeled Instance of Bicycle: False"); 66 | 67 | if (myTwoWheeled instanceof TwoWheeled) 68 | System.out.println("myTwoWheeled Instance of TwoWheeled: True"); 69 | else 70 | System.out.println("myTwoWheeled Instance of TwoWheeled: False"); 71 | 72 | if (myTwoWheeled instanceof Vehicle) 73 | System.out.println("myTwoWheeled Instance of Vehicle: True"); 74 | else 75 | System.out.println("myTwoWheeled Instance of Vehicle: False"); 76 | 77 | if (myTwoWheeled instanceof Object) 78 | System.out.println("myTwoWheeled Instance of Object: True"); 79 | else 80 | System.out.println("myTwoWheeled Instance of Object: False"); 81 | 82 | // focus on Vehicle 83 | Vehicle myVehicle = new Vehicle(); 84 | 85 | if (myVehicle instanceof Bicycle) 86 | System.out.println("\nmyVehicle Instance of Bicycle: True"); 87 | else 88 | System.out.println("\nmyVehicle Instance of Bicycle: False"); 89 | 90 | if (myVehicle instanceof TwoWheeled) 91 | System.out.println("myVehicle Instance of TwoWheeled: True"); 92 | else 93 | System.out.println("myVehicle Instance of TwoWheeled: False"); 94 | 95 | if (myVehicle instanceof Vehicle) 96 | System.out.println("myVehicle Instance of Vehicle: True"); 97 | else 98 | System.out.println("myVehicle Instance of Vehicle: False"); 99 | 100 | if (myVehicle instanceof Object) 101 | System.out.println("myVehicle Instance of Object: True"); 102 | else 103 | System.out.println("myVehicle Instance of Object: False"); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /Chapter02/TwoWheeled.java: -------------------------------------------------------------------------------- 1 | package com.three19; 2 | 3 | public class TwoWheeled extends Vehicle { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter02/Vehicle.java: -------------------------------------------------------------------------------- 1 | package com.three19; 2 | 3 | public class Vehicle { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/AcademicEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public class AcademicEmailHandler extends MainEmailHandler { 4 | 5 | protected String[] keyWords() { 6 | // setup keywords for the receiver team 7 | return new String[] {"academic"}; 8 | } 9 | 10 | protected void processEmailFinal(String emailText) { 11 | System.out.println("The Academic Team processed the email."); 12 | } 13 | 14 | @Override 15 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/AdminEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public class AdminEmailHandler extends MainEmailHandler { 4 | 5 | protected String[] keyWords() { 6 | // Here it does not matter what the keywords are 7 | return new String[0]; 8 | } 9 | 10 | protected void processEmailFinal(String emailText) { 11 | System.out.println("The Admin Team processed the email."); 12 | } 13 | 14 | @Override 15 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/AdvisingEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public class AdvisingEmailHandler extends MainEmailHandler { 4 | 5 | protected String[] keyWords() { 6 | // setup keywords for the receiver team 7 | return new String[] {"advising", "schedule", "course"}; 8 | } 9 | 10 | protected void processEmailFinal(String emailText) { 11 | System.out.println("The Advising Team processed the email."); 12 | } 13 | 14 | @Override 15 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/AlumniEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public class AlumniEmailHandler extends MainEmailHandler { 4 | 5 | protected String[] keyWords() { 6 | // setup keywords for the receiver team 7 | return new String[] {"alumni", "transcript"}; 8 | } 9 | 10 | protected void processEmailFinal(String emailText) { 11 | System.out.println("The Alumni Team processed the email."); 12 | } 13 | 14 | @Override 15 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/FinanceEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public class FinanceEmailHandler extends MainEmailHandler { 4 | 5 | protected String[] keyWords() { 6 | // setup keywords for the receiver team 7 | return new String[] {"financial", "student aid", "tuition"}; 8 | } 9 | 10 | protected void processEmailFinal(String emailText) { 11 | System.out.println("The Finance Team processed the email."); 12 | } 13 | 14 | @Override 15 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/HREmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public class HREmailHandler extends MainEmailHandler { 4 | 5 | protected String[] assignedKeyWords() { 6 | // setup keywords for the receiver team 7 | return new String[]{"career", "job", "faculty"}; 8 | } 9 | 10 | @Override 11 | protected String[] keyWords() { 12 | return new String[0]; 13 | } 14 | 15 | protected void processEmailFinal(String emailText) { 16 | System.out.println("The Human Resources Team processed the email."); 17 | } 18 | 19 | @Override 20 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/MainEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public abstract class MainEmailHandler implements UniversityEmailHandler { 4 | 5 | private UniversityEmailHandler theNextHandlerInTheChain; 6 | 7 | public void setNextEmailHandler(UniversityEmailHandler emailHandler) { 8 | theNextHandlerInTheChain = emailHandler; 9 | } 10 | 11 | public void processEmailHandler(String emailText) { 12 | 13 | // starting value 14 | boolean keyWordFound = false; 15 | 16 | // check for a matching keyword in emailText 17 | if (keyWords().length == 0) { 18 | keyWordFound = true; 19 | } else { 20 | for (String oneKeyWord : keyWords()) { 21 | if (emailText.indexOf(oneKeyWord) >= 0) { 22 | keyWordFound = true; // change value if match is found 23 | break; // leave loop if match is found 24 | } 25 | } 26 | } 27 | 28 | // check to see if email can be processed by the current 29 | // email handler based on keyword match 30 | if (keyWordFound) { 31 | processEmailHandler(emailText); 32 | } else { 33 | // pass along the chain if the email is not processed 34 | // by the current email handler 35 | theNextHandlerInTheChain.processEmailHandler(emailText); 36 | } 37 | } 38 | 39 | public static void handleEmail(String emailText) { 40 | UniversityEmailHandler academic = new AcademicEmailHandler(); 41 | UniversityEmailHandler alumni = new AlumniEmailHandler(); 42 | UniversityEmailHandler advising = new AdvisingEmailHandler(); 43 | UniversityEmailHandler finance = new FinanceEmailHandler(); 44 | UniversityEmailHandler hr = new HREmailHandler(); 45 | UniversityEmailHandler admin = new AdminEmailHandler(); 46 | 47 | // setup chain direction 48 | academic.setNextEmailHandler(alumni); 49 | alumni.setNextEmailHandler(advising); 50 | advising.setNextEmailHandler(finance); 51 | finance.setNextEmailHandler(hr); 52 | hr.setNextEmailHandler(admin); 53 | // we do not need to set the next email handler after admin 54 | // because it is the end of the chain of responsibility 55 | 56 | // this line will start the chain 57 | academic.processEmailHandler(emailText); 58 | } 59 | protected abstract String[] keyWords(); 60 | protected abstract void processEmailFinal(String emailText); 61 | } 62 | -------------------------------------------------------------------------------- /Chapter03/CH3ChainResponsibility/UniversityEmailHandler.java: -------------------------------------------------------------------------------- 1 | package CH3ChainResponsibility; 2 | 3 | public interface UniversityEmailHandler { 4 | 5 | public void setNextEmailHandler(UniversityEmailHandler emailHandler); 6 | 7 | public void processEmailHandler(String emailText); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /Chapter03/CH3Command/ControlBox.java: -------------------------------------------------------------------------------- 1 | package CH3Command; 2 | 3 | public class ControlBox { 4 | 5 | // Class Variables - Public / Final 6 | public static final int SLIDER_MIN = 0; 7 | public static final int SLIDER_MAX = 100; 8 | 9 | // Class Variables - Private 10 | private boolean poweredOn; 11 | private int sliderValue; 12 | 13 | // Constructor 14 | public ControlBox () { 15 | poweredOn = false; // default value 16 | sliderValue = 0; // default value 17 | } 18 | 19 | // Accessor Methods 20 | public int getSliderValue() { 21 | return sliderValue; 22 | } 23 | 24 | public boolean hasPower () { 25 | return poweredOn; 26 | } 27 | 28 | // Method to turn power on 29 | public void powerOn() { 30 | poweredOn = true; 31 | } 32 | 33 | // Method to turn power off 34 | public void powerOff() { 35 | poweredOn = false; 36 | } 37 | 38 | // Method to increase slider value 39 | public void sliderIncrease () { 40 | if (hasPower()) { 41 | if (getSliderValue() < SLIDER_MAX) { 42 | sliderValue++; 43 | System.out.println(sliderValue); // simulate sending value to digital display 44 | } 45 | } 46 | } 47 | 48 | // Method to decrease slider value 49 | public void sliderDecrease () { 50 | if (hasPower()) { 51 | if (getSliderValue() > SLIDER_MIN) { 52 | sliderValue--; 53 | System.out.println(sliderValue); // simulate sending value to digital display 54 | } 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /Chapter03/CH3Interpreter/Conversion.java: -------------------------------------------------------------------------------- 1 | package CH3Interpreter; 2 | 3 | public class Conversion { 4 | 5 | // class variable 6 | public String userInput; 7 | 8 | // constructor 9 | public Conversion(String userInput) { 10 | this.userInput = userInput; 11 | } 12 | 13 | public void convertToCharacters(String userInput) { 14 | 15 | this.userInput = userInput; 16 | 17 | System.out.print("Decrypted Message: "); 18 | char answer[] = userInput.toCharArray(); 19 | 20 | for (int i=0; i < answer.length; i++) { 21 | switch (answer[i]) { 22 | case '0': 23 | System.out.print("A"); 24 | break; 25 | case '1': 26 | System.out.print("E"); 27 | break; 28 | case '2': 29 | System.out.print("I"); 30 | break; 31 | case '3': 32 | System.out.print("Y"); 33 | break; 34 | case '4': 35 | System.out.print("O"); 36 | break; 37 | case '5': 38 | System.out.print("L"); 39 | break; 40 | case '6': 41 | System.out.print("R"); 42 | break; 43 | case '7': 44 | System.out.print("T"); 45 | break; 46 | case '8': 47 | System.out.print("C"); 48 | break; 49 | case '9': 50 | System.out.print("S"); 51 | break; 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Chapter03/CH3Interpreter/Expression.java: -------------------------------------------------------------------------------- 1 | package CH3Interpreter; 2 | 3 | interface Expression { 4 | 5 | void interpret(Conversion orignalContent); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /Chapter03/CH3Interpreter/InterpreterDriver.java: -------------------------------------------------------------------------------- 1 | package CH3Interpreter; 2 | 3 | import java.util.Scanner; 4 | 5 | public class InterpreterDriver { 6 | 7 | // class variables 8 | public Conversion originatingContent = null; 9 | public Expression theExpression = null; 10 | 11 | public InterpreterDriver(Conversion content) { 12 | originatingContent = content; 13 | } 14 | 15 | public void interpret(String tString) { 16 | 17 | Scanner in = new Scanner(System.in); 18 | theExpression = new MapIntToCharacters(tString); 19 | theExpression.interpret(originatingContent); 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println("\n\nCODE INTERPRETER\n"); 24 | System.out.print("Enter your code: "); 25 | Scanner in = new Scanner(System.in); 26 | String userInput = in.nextLine(); 27 | System.out.println("Your code: " + userInput); 28 | Conversion conversion = new Conversion(userInput); 29 | InterpreterDriver userCode = new InterpreterDriver(conversion); 30 | userCode.interpret(userInput); 31 | System.out.println("\n\n"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter03/CH3Interpreter/MapIntToCharacters.java: -------------------------------------------------------------------------------- 1 | package CH3Interpreter; 2 | 3 | public class MapIntToCharacters implements Expression { 4 | 5 | // class variable 6 | private String tString; 7 | 8 | // constructor 9 | public MapIntToCharacters(String tString) { 10 | this.tString = tString; 11 | } 12 | 13 | @Override 14 | public void interpret(Conversion orignalContent) { 15 | orignalContent.convertToCharacters(tString); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter03/CH3Iterator/IteratorExample.java: -------------------------------------------------------------------------------- 1 | package CH3Iterator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | 6 | public class IteratorExample { 7 | 8 | public static void main(String[] args) { 9 | 10 | ArrayList colonies = new ArrayList<>(); 11 | 12 | colonies.add("Aerlion"); 13 | colonies.add("Aquaria"); 14 | colonies.add("Canceron"); 15 | colonies.add("Caprica"); 16 | colonies.add("Gemenon"); 17 | colonies.add("Leonis"); 18 | colonies.add("Libran"); 19 | colonies.add("Picon"); 20 | colonies.add("Sagittaron"); 21 | colonies.add("Scorpia"); 22 | colonies.add("Tauron"); 23 | colonies.add("Virgon"); 24 | 25 | // instantiate iterator 26 | Iterator myIterator = colonies.iterator(); 27 | 28 | // console output 29 | System.out.println("\n\nOriginal Colonies of Kobol:"); 30 | 31 | // iterate through the list 32 | while (myIterator.hasNext()) 33 | System.out.println("\t\t" + myIterator.next()); 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chapter03/CH3Mediator/AssemblySystem.java: -------------------------------------------------------------------------------- 1 | package CH3Mediator; 2 | 3 | public class AssemblySystem { 4 | 5 | public enum SystemSpeed {ZERO, ONE, TWO, THREE, FOUR, FIVE, 6 | SIX, SEVEN, EIGHT, NINE, TEN}; 7 | 8 | private WidgetProductionSystem mediator; 9 | private boolean enabled; 10 | private SystemSpeed currentSpeed; 11 | 12 | // constructor 13 | public AssemblySystem(WidgetProductionSystem mediator) { 14 | this.mediator = mediator; 15 | enabled = false; 16 | currentSpeed = SystemSpeed.ZERO; 17 | mediator.mediateAssemblySystem(this); 18 | } 19 | 20 | // accessor 21 | public SystemSpeed getSystemSpeed() { 22 | return currentSpeed; 23 | } 24 | 25 | // mutator 26 | public void setSystemSpeed(SystemSpeed speed) { 27 | if ((isEnabled()) && (getSystemSpeed() != speed)) { 28 | currentSpeed = speed; 29 | mediator.assemblySystemSpeedChanged(); 30 | System.out.println("Mediated Event: System Speed Changed to " + currentSpeed + "."); 31 | } 32 | } 33 | 34 | // additional methods 35 | public void enable() { 36 | enabled = true; 37 | mediator.assemblySystemEnabled(); 38 | System.out.println("Mediated Event: System Initialized."); 39 | } 40 | 41 | public void disable() { 42 | enabled = false; 43 | mediator.assemblySystemDisabled(); 44 | System.out.println("Mediated Event: System Deinitialized."); 45 | } 46 | 47 | public boolean isEnabled() { 48 | return enabled; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Chapter03/CH3Mediator/EmergencyBreak.java: -------------------------------------------------------------------------------- 1 | package CH3Mediator; 2 | 3 | public class EmergencyBreak { 4 | 5 | // class variables 6 | private WidgetProductionSystem mediator; 7 | private boolean enabled; 8 | private boolean applied; 9 | 10 | // constructor 11 | public EmergencyBreak(WidgetProductionSystem mediator) { 12 | this.mediator = mediator; 13 | enabled = false; 14 | applied = false; 15 | mediator.mediateEmergencyBreak(this); 16 | } 17 | 18 | public void enable() { 19 | enabled = true; 20 | mediator.setEmergencyBreakEnabled(); 21 | System.out.println("Mediated Event: System Decelerator Enabled."); 22 | } 23 | 24 | public void disable() { 25 | enabled = false; 26 | mediator.setEmergencyBreakDisabled(); 27 | System.out.println("Mediated Event: System Decelerator Disabled."); 28 | } 29 | 30 | public boolean isEnabled() { 31 | return enabled; 32 | } 33 | 34 | public void apply() { 35 | if (isEnabled()) { 36 | applied = true; 37 | mediator.setEmergencyBreakEngaged(); 38 | System.out.println("Mediated Event: Emergency Break Engaged."); 39 | } 40 | } 41 | public void release() { 42 | if (isEnabled()) { 43 | applied = false; 44 | mediator.setEmergencyBreakDisengaged(); 45 | System.out.println("Mediated Event: Emergency Break Disengaged."); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Chapter03/CH3Mediator/Hopper.java: -------------------------------------------------------------------------------- 1 | package CH3Mediator; 2 | 3 | public class Hopper { 4 | 5 | private WidgetProductionSystem mediator; 6 | private boolean enabled; 7 | 8 | // constructor 9 | public Hopper(WidgetProductionSystem mediator) { 10 | this.mediator = mediator; 11 | enabled = false; 12 | mediator.mediateHopper(this); 13 | } 14 | 15 | // accessor 16 | public boolean getHopperEnabled() { 17 | return enabled; 18 | } 19 | 20 | public void enable() { 21 | enabled = true; 22 | mediator.hopperEnabled(); 23 | System.out.println("Mediated Event: Hopper Initialized."); 24 | } 25 | 26 | public void disable() { 27 | enabled = false; 28 | mediator.hopperDisabled(); 29 | System.out.println("Mediated Event: Hopper Deinitialized."); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Chapter03/CH3Mediator/Starter.java: -------------------------------------------------------------------------------- 1 | package CH3Mediator; 2 | 3 | public class Starter { 4 | 5 | private WidgetProductionSystem mediator; 6 | private boolean poweredOn; 7 | 8 | // Constructor 9 | public Starter(WidgetProductionSystem mediator) { 10 | this.mediator = mediator; 11 | poweredOn = false; 12 | 13 | mediator.mediateStarter(this); 14 | } 15 | 16 | // accessor 17 | public boolean isSystemOn() { 18 | return poweredOn; 19 | } 20 | 21 | public void turnOn() { 22 | poweredOn = true; 23 | mediator.starterPoweredOn(); 24 | System.out.println("Mediated Event: Started Powered On"); 25 | } 26 | 27 | public void turnOff() { 28 | poweredOn = false; 29 | mediator.starterPoweredOff(); 30 | System.out.println("Mediated Event: Starter Powered Off"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Chapter03/CH3Mediator/SystemAccelerator.java: -------------------------------------------------------------------------------- 1 | package CH3Mediator; 2 | 3 | public class SystemAccelerator { 4 | 5 | // class variables 6 | private WidgetProductionSystem mediator; 7 | private boolean enabled; 8 | private int speed; 9 | 10 | // constructor 11 | public SystemAccelerator(WidgetProductionSystem mediator) { 12 | this.mediator = mediator; 13 | enabled = false; 14 | speed = 0; 15 | mediator.mediateSystemAcceleration(this); 16 | } 17 | 18 | // accessor 19 | public int getAcceleratorSpeed() { 20 | return speed; 21 | } 22 | 23 | public boolean isEnabled() { 24 | return enabled; 25 | } 26 | 27 | public void enable() { 28 | enabled = true; 29 | mediator.systemAcceleratorEnabled(); 30 | System.out.println("Mediated Event: System Accelerator Enabled."); 31 | } 32 | 33 | public void disable() { 34 | enabled = false; 35 | mediator.systemAcceleratorDisabled(); 36 | System.out.println("Mediated Event: System Accelerator Disabled."); 37 | } 38 | 39 | 40 | 41 | public void accelerateToSpeed(int speed) { 42 | if (isEnabled()) { 43 | this.speed = speed; 44 | mediator.systemAcceleratorUsed(); 45 | System.out.println("Mediated Event: System Accelerator Set to " + speed + "."); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Chapter03/CH3Mediator/WidgetProductionSystem.java: -------------------------------------------------------------------------------- 1 | package CH3Mediator; 2 | 3 | public class WidgetProductionSystem { 4 | 5 | // class variables 6 | private Starter starter; 7 | private AssemblySystem assemblySystem; 8 | private SystemAccelerator systemAccelerator; 9 | private EmergencyBreak emergencyBreak; 10 | private Hopper hopper; 11 | 12 | private int currentSpeed; 13 | 14 | // constructor 15 | public WidgetProductionSystem() { 16 | currentSpeed = 0; 17 | } 18 | 19 | // mediation methods 20 | public void mediateStarter(Starter starter) { 21 | this.starter = starter; 22 | } 23 | 24 | public void mediateAssemblySystem(AssemblySystem assemblySystem) { 25 | this.assemblySystem = assemblySystem; 26 | } 27 | 28 | public void mediateSystemAcceleration(SystemAccelerator systemAccelerator) { 29 | this.systemAccelerator = systemAccelerator; 30 | } 31 | 32 | public void mediateEmergencyBreak(EmergencyBreak emergencyBreak) { 33 | this.emergencyBreak = emergencyBreak; 34 | } 35 | 36 | public void mediateHopper(Hopper hopper) { this.hopper = hopper; } 37 | 38 | // object interaction methods 39 | public void starterPoweredOn() { 40 | assemblySystem.enable(); 41 | hopper.enable(); 42 | systemAccelerator.enable(); 43 | emergencyBreak.enable(); 44 | } 45 | 46 | public void starterPoweredOff() { 47 | assemblySystem.disable(); 48 | hopper.disable(); 49 | systemAccelerator.disable(); 50 | emergencyBreak.disable(); 51 | } 52 | 53 | public void assemblySystemEnabled() { 54 | System.out.println("Mediation Decision: Hopper Enabled."); 55 | } 56 | 57 | public void assemblySystemDisabled() { 58 | System.out.println("Mediation Decision: Hopper Disabled."); 59 | } 60 | 61 | public void hopperEnabled() { 62 | System.out.println("Mediation Decision: Assembly System Enabled."); 63 | } 64 | 65 | public void hopperDisabled() { 66 | System.out.println("Mediation Decision: Assembly System Disabled."); 67 | } 68 | 69 | public void assemblySystemSpeedChanged() { 70 | System.out.println("Mediation Decision: Permissible Speed Change."); 71 | } 72 | 73 | public void systemAcceleratorEnabled() { 74 | System.out.println("Mediation Decision: Emergency Break Enabled"); 75 | } 76 | 77 | public void systemAcceleratorDisabled() { 78 | System.out.println("Mediation Decision: Emergency Break Disabled"); 79 | } 80 | 81 | public void systemAcceleratorUsed() { 82 | emergencyBreak.disable(); 83 | while (currentSpeed < systemAccelerator.getAcceleratorSpeed()) { 84 | currentSpeed ++; 85 | System.out.println("Mediation Event: Speed Changed to " + currentSpeed + "."); 86 | 87 | if (currentSpeed <= 10) { 88 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.ONE); 89 | } else if (currentSpeed <= 20) { 90 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.TWO); 91 | } else if (currentSpeed <= 30) { 92 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.THREE); 93 | } else if (currentSpeed <= 40) { 94 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.FOUR); 95 | } else if (currentSpeed <= 50) { 96 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.FIVE); 97 | } else if (currentSpeed <= 60) { 98 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.SIX); 99 | } else if (currentSpeed <= 70) { 100 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.SEVEN); 101 | } else if (currentSpeed <= 80) { 102 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.EIGHT); 103 | } else if (currentSpeed <= 90) { 104 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.NINE); 105 | } else { assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.TEN); } 106 | } 107 | emergencyBreak.enable(); 108 | } 109 | 110 | public void setEmergencyBreakEnabled() { 111 | System.out.println("Mediation Decision: System Accelerator Disabled."); 112 | } 113 | 114 | public void setEmergencyBreakDisabled() { 115 | System.out.println("Mediation Decision: System Accelerator Enabled."); 116 | } 117 | 118 | public void setEmergencyBreakEngaged() { 119 | systemAccelerator.disable(); 120 | currentSpeed = 0; 121 | } 122 | 123 | public void setEmergencyBreakDisengaged() { 124 | assemblySystem.setSystemSpeed(AssemblySystem.SystemSpeed.ZERO); 125 | currentSpeed = 0; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /Chapter03/CH3Memento/GameMission.java: -------------------------------------------------------------------------------- 1 | package CH3Memento; 2 | 3 | public class GameMission { 4 | 5 | // class variables 6 | private int percentageCompleted; 7 | int previousPercentageCompleted; 8 | 9 | // constructor 10 | public GameMission() { 11 | percentageCompleted = 0; 12 | previousPercentageCompleted = 0; 13 | } 14 | 15 | // mutator 16 | public void setPercentageCompeted(int percentage) { 17 | previousPercentageCompleted = percentageCompleted; 18 | percentageCompleted = percentage; 19 | } 20 | 21 | // accessor 22 | public int getPercentageCompleted() { 23 | return percentageCompleted; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter03/CH3Memento/GameMissionMemento.java: -------------------------------------------------------------------------------- 1 | package CH3Memento; 2 | 3 | public class GameMissionMemento { 4 | 5 | // class variables 6 | private GameMission gameMission; 7 | private int copyOfCurrentCompletionProgress; 8 | private int copyOfPreviousCompletionProgress; 9 | 10 | // constructor 11 | public GameMissionMemento(GameMission gameMission) { 12 | this.gameMission = gameMission; 13 | copyOfCurrentCompletionProgress = gameMission.getPercentageCompleted(); 14 | copyOfPreviousCompletionProgress = gameMission.previousPercentageCompleted; 15 | } 16 | 17 | public void resetMissionStatus() { 18 | gameMission.setPercentageCompeted(copyOfCurrentCompletionProgress); 19 | gameMission.previousPercentageCompleted = copyOfPreviousCompletionProgress; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter03/CH3NullObject/EasternTrain.java: -------------------------------------------------------------------------------- 1 | package CH3NullObject; 2 | 3 | public class EasternTrain implements TrainStatus { 4 | 5 | private boolean activated; 6 | 7 | public void activate() { 8 | activated = true; 9 | System.out.println("Train Status Update: Eastern Train Activated."); 10 | } 11 | 12 | public void deactivate() { 13 | activated = false; 14 | System.out.println("Train Status Update: Eastern Train Deactivated."); 15 | } 16 | 17 | public boolean isActivated() { 18 | return activated; 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter03/CH3NullObject/NorthernTrain.java: -------------------------------------------------------------------------------- 1 | package CH3NullObject; 2 | 3 | public class NorthernTrain implements TrainStatus { 4 | 5 | private boolean activated; 6 | 7 | public void activate() { 8 | activated = true; 9 | System.out.println("Train Status Update: Northern Train Activated."); 10 | } 11 | 12 | public void deactivate() { 13 | activated = false; 14 | System.out.println("Train Status Update: Northern Train Deactivated."); 15 | } 16 | 17 | public boolean isActivated() { 18 | return activated; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter03/CH3NullObject/NullObjectTrain.java: -------------------------------------------------------------------------------- 1 | package CH3NullObject; 2 | 3 | public class NullObjectTrain implements TrainStatus { 4 | 5 | public void activate() { 6 | // no functionality 7 | } 8 | 9 | public void deactivate() { 10 | // no functionality 11 | } 12 | 13 | public boolean isActivated() { 14 | return false; 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter03/CH3NullObject/SouthernTrain.java: -------------------------------------------------------------------------------- 1 | package CH3NullObject; 2 | 3 | public class SouthernTrain implements TrainStatus { 4 | 5 | private boolean activated; 6 | 7 | public void activate() { 8 | activated = true; 9 | System.out.println("Train Status Update: Southern Train Activated."); 10 | } 11 | 12 | public void deactivate() { 13 | activated = false; 14 | System.out.println("Train Status Update: Southern Train Deactivated."); 15 | } 16 | 17 | public boolean isActivated() { 18 | return activated; 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter03/CH3NullObject/TrainStatus.java: -------------------------------------------------------------------------------- 1 | package CH3NullObject; 2 | 3 | public interface TrainStatus { 4 | 5 | public void activate(); 6 | public void deactivate(); 7 | public boolean isActivated(); 8 | } 9 | -------------------------------------------------------------------------------- /Chapter03/CH3NullObject/WesternTrain.java: -------------------------------------------------------------------------------- 1 | package CH3NullObject; 2 | 3 | public class WesternTrain implements TrainStatus { 4 | 5 | private boolean activated; 6 | 7 | public void activate() { 8 | activated = true; 9 | System.out.println("Train Status Update: Western Train Activated."); 10 | } 11 | 12 | public void deactivate() { 13 | activated = false; 14 | System.out.println("Train Status Update: Western Train Deactivated."); 15 | } 16 | 17 | public boolean isActivated() { 18 | return activated; 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter03/CH3Observer/ForumMonitor.java: -------------------------------------------------------------------------------- 1 | package CH3Observer; 2 | 3 | public class ForumMonitor implements Observer { 4 | 5 | public static final int UNREAD_ALERT_LEVEL = 0; 6 | 7 | public void update(Observable observable, Object object) { 8 | StudentDashboard messages = (StudentDashboard) observable; 9 | if (messages.getUnreadMessages() > UNREAD_ALERT_LEVEL) { 10 | System.out.println("You have " + messages.getUnreadMessages() + " unread messages."); 11 | } else { 12 | System.out.println("No unread messages found."); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter03/CH3Observer/Observable.java: -------------------------------------------------------------------------------- 1 | package CH3Observer; 2 | 3 | public class Observable { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter03/CH3Observer/Observer.java: -------------------------------------------------------------------------------- 1 | package CH3Observer; 2 | 3 | public interface Observer { 4 | } 5 | -------------------------------------------------------------------------------- /Chapter03/CH3Observer/StudentDashboard.java: -------------------------------------------------------------------------------- 1 | package CH3Observer; 2 | 3 | public class StudentDashboard extends Observable { 4 | 5 | private int unreadMessages; 6 | 7 | // constructor 8 | public StudentDashboard() { 9 | unreadMessages = 0; 10 | } 11 | 12 | public void setUnreadMessages(int messages) { 13 | unreadMessages = messages; 14 | 15 | /* 16 | Add methods here to notify observers of a change 17 | */ 18 | 19 | } 20 | 21 | public int getUnreadMessages() { 22 | return unreadMessages; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter03/CH3State/Driver.java: -------------------------------------------------------------------------------- 1 | package CH3State; 2 | 3 | public class Driver { 4 | 5 | public static void main(String[] args) { 6 | 7 | PrinterOffLine initialPrinterState = new PrinterOffLine(); 8 | Printer printer = new Printer(initialPrinterState); 9 | 10 | System.out.println("\n"); 11 | 12 | printer.pushPrint(); 13 | printer.pushPrint(); 14 | printer.pushPrint(); 15 | 16 | System.out.println("\n\n"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter03/CH3State/Printer.java: -------------------------------------------------------------------------------- 1 | package CH3State; 2 | 3 | public class Printer { 4 | 5 | // class variable 6 | private PrinterController printerState; 7 | 8 | // constructor 9 | public Printer(PrinterController pState) { 10 | this.printerState = pState; 11 | } 12 | 13 | // accessor / getter 14 | public PrinterController getPrinterState() { 15 | return printerState; 16 | } 17 | 18 | // mutator / setter 19 | public void setPrinterState(PrinterController pState) { 20 | this.printerState = pState; 21 | } 22 | 23 | public void pushPrint() { 24 | printerState.pushPrint(this); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Chapter03/CH3State/PrinterController.java: -------------------------------------------------------------------------------- 1 | package CH3State; 2 | 3 | abstract class PrinterController { 4 | 5 | public abstract void pushPrint(Printer printJob); 6 | } 7 | -------------------------------------------------------------------------------- /Chapter03/CH3State/PrinterOffLine.java: -------------------------------------------------------------------------------- 1 | package CH3State; 2 | 3 | public class PrinterOffLine extends PrinterController { 4 | 5 | @Override 6 | public void pushPrint(Printer printJob) { 7 | System.out.println("\nPowering printer on please wait. . ."); 8 | printJob.setPrinterState(new PrinterOnLine()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter03/CH3State/PrinterOnLine.java: -------------------------------------------------------------------------------- 1 | package CH3State; 2 | 3 | public class PrinterOnLine extends PrinterController { 4 | 5 | @Override 6 | public void pushPrint(Printer printJob) { 7 | System.out.println("\nClearing buffer and shutting down. . ."); 8 | printJob.setPrinterState(new PrinterOffLine()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Daughter.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class Daughter { 4 | 5 | public static void main(String[] args) { 6 | Mother mom = new Mother(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Engine.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public interface Engine { 4 | public String getEngine(); 5 | } 6 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Frame.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public interface Frame { 4 | public String getFrame(); 5 | } 6 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Grandmother.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | abstract class Grandmother { 4 | 5 | // Constructor 6 | Grandmother() { 7 | System.out.println("Grandmother constructor executed."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Kitchen.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public interface Kitchen { 4 | public String getKitchen(); 5 | } 6 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Mother.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class Mother extends Grandmother { 4 | 5 | // Constructor 6 | Mother() { 7 | System.out.println("Mother constructor executed."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/MotorHomeAbstractFactory.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public abstract class MotorHomeAbstractFactory { 4 | public abstract Frame createFrame(); 5 | public abstract Style createStyle(); 6 | public abstract Engine createEngine(); 7 | public abstract Kitchen createKitchen(); 8 | } 9 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/MotorHomeDriver.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class MotorHomeDriver { 4 | 5 | public static void main(String[] args) { 6 | 7 | // Step 1 8 | // create abstract factory 9 | MotorHomeAbstractFactory mhFactory = null; 10 | 11 | // Step 2 12 | // Create a factory instance 13 | String nextMotorHome = "TypeA"; // simulated user input 14 | 15 | if (nextMotorHome.equals("TypeA")) { 16 | System.out.println("\nType A motor home selected"); 17 | mhFactory = new TypeAFactory(); 18 | } else if (nextMotorHome.equals("TypeB")) { 19 | System.out.println("\nType B motor home selected"); 20 | mhFactory = new TypeBFactory(); 21 | } else if (nextMotorHome.equals("TypeC")) { 22 | System.out.println("\nType C motor home selected"); 23 | mhFactory = new TypeCFactory(); 24 | } else { 25 | System.out.println("Invalid motor home type entered."); 26 | } 27 | 28 | // Step 3 29 | // Create motor home components 30 | Style mhStyle = mhFactory.createStyle(); 31 | Frame mhFrame = mhFactory.createFrame(); 32 | Engine mhEngine = mhFactory.createEngine(); 33 | Kitchen mhKitchen = mhFactory.createKitchen(); 34 | 35 | // Step 4 36 | // Provide Output 37 | System.out.println("\nComponent list for " + nextMotorHome + " motor home"); 38 | System.out.println(mhStyle.getStyle()); 39 | System.out.println(mhFrame.getFrame()); 40 | System.out.println(mhEngine.getEngine()); 41 | System.out.println(mhKitchen.getKitchen()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Style.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public interface Style { 4 | public String getStyle(); 5 | } 6 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/Type.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public interface Type { 4 | public String getType(); 5 | } 6 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeAEngine.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeAEngine implements Engine { 4 | 5 | public String getEngine() { 6 | 7 | return "[Type A] Engine:\tFord V10"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeAFactory.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeAFactory extends MotorHomeAbstractFactory { 4 | 5 | 6 | public Frame createFrame() { 7 | return new TypeAFrame(); 8 | } 9 | 10 | public Style createStyle() { 11 | return new TypeAStyle(); 12 | } 13 | 14 | public Engine createEngine() { 15 | return new TypeAEngine(); 16 | } 17 | 18 | public Kitchen createKitchen() { 19 | return new TypeAKitchen(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeAFrame.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeAFrame implements Frame { 4 | 5 | public String getFrame() { 6 | 7 | return "[Type A] Frame:\t\tBus"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeAKitchen.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeAKitchen implements Kitchen { 4 | 5 | public String getKitchen() { 6 | 7 | return "[Type A] Kitchen:\tFull"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeAStyle.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeAStyle implements Style { 4 | 5 | public String getStyle() { 6 | 7 | return "[Type A] Style:\t\tOff the Grid"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeBEngine.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeBEngine implements Engine { 4 | 5 | public String getEngine() { 6 | 7 | return "[Type B] Engine:\tFord Transit 350 HD"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeBFactory.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeBFactory extends MotorHomeAbstractFactory { 4 | 5 | 6 | public Frame createFrame() { 7 | return new TypeBFrame(); 8 | } 9 | 10 | public Style createStyle() { 11 | return new TypeBStyle(); 12 | } 13 | 14 | public Engine createEngine() { 15 | return new TypeBEngine(); 16 | } 17 | 18 | public Kitchen createKitchen() { 19 | return new TypeBKitchen(); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeBFrame.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeBFrame implements Frame { 4 | 5 | public String getFrame() { 6 | 7 | return "[Type B] Frame:\t\tCamper Van"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeBKitchen.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeBKitchen implements Kitchen { 4 | 5 | public String getKitchen() { 6 | 7 | return "[Type B] Kitchen:\tCompact"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeBStyle.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeBStyle implements Style { 4 | 5 | public String getStyle() { 6 | 7 | return "[Type B] Style:\t\tWeekender"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeCEngine.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeCEngine implements Engine { 4 | 5 | public String getEngine() { 6 | 7 | return "[Type C] Engine:\tFord E-450"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeCFactory.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeCFactory extends MotorHomeAbstractFactory { 4 | 5 | 6 | public Frame createFrame() { 7 | return new TypeCFrame(); 8 | } 9 | 10 | public Style createStyle() { 11 | return new TypeCStyle(); 12 | } 13 | 14 | public Engine createEngine() { 15 | return new TypeCEngine(); 16 | } 17 | 18 | public Kitchen createKitchen() { 19 | return new TypeCKitchen(); 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeCFrame.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeCFrame implements Frame { 4 | 5 | public String getFrame() { 6 | 7 | return "[Type C] Frame:\t\tTruck"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeCKitchen.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeCKitchen implements Kitchen { 4 | 5 | public String getKitchen() { 6 | 7 | return "[Type C] Kitchen:\tFull"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4AbstractFactory/TypeCStyle.java: -------------------------------------------------------------------------------- 1 | package CH4AbstractFactory; 2 | 3 | public class TypeCStyle implements Style { 4 | 5 | public String getStyle() { 6 | 7 | return "[Type C] Style:\t\tExtended Trip"; 8 | } 9 | } -------------------------------------------------------------------------------- /Chapter04/CH4Builder/Builder.java: -------------------------------------------------------------------------------- 1 | package CH4Builder; 2 | 3 | public interface Builder { 4 | 5 | void buildCoolingTray(); 6 | void buildExhaustSystem(); 7 | void buildGasBurner(); 8 | void buildPlatform(); 9 | void buildMotor(); 10 | void buildThermocouples(); 11 | void buildInnerDrum(); 12 | void buildMainBody(); 13 | 14 | Roaster getRoaster(); 15 | } 16 | -------------------------------------------------------------------------------- /Chapter04/CH4Builder/CommercialRoaster.java: -------------------------------------------------------------------------------- 1 | package CH4Builder; 2 | 3 | public class CommercialRoaster implements Builder { 4 | 5 | private Roaster roaster = new Roaster(); 6 | 7 | @Override 8 | public void buildCoolingTray() { 9 | roaster.add("Commercial Roaster Cooling Tray added"); 10 | 11 | } 12 | 13 | @Override 14 | public void buildExhaustSystem() { 15 | roaster.add("Commercial Roaster Exhaust System added"); 16 | 17 | } 18 | 19 | @Override 20 | public void buildGasBurner() { 21 | roaster.add("Commercial Roaster Gas Burner added"); 22 | 23 | } 24 | 25 | @Override 26 | public void buildPlatform() { 27 | roaster.add("Standard Platform added"); 28 | 29 | } 30 | 31 | @Override 32 | public void buildMotor() { 33 | roaster.add("Standard Motor added"); 34 | 35 | } 36 | 37 | @Override 38 | public void buildThermocouples() { 39 | roaster.add("Standard Thermocouples added"); 40 | 41 | } 42 | 43 | @Override 44 | public void buildInnerDrum() { 45 | roaster.add("Commercial Roaster Inner Drum added"); 46 | } 47 | 48 | @Override 49 | public void buildMainBody() { 50 | roaster.add("Commercial Roaster Main body added"); 51 | 52 | } 53 | 54 | @Override 55 | public Roaster getRoaster() { 56 | return roaster; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Chapter04/CH4Builder/PersonalRoaster.java: -------------------------------------------------------------------------------- 1 | package CH4Builder; 2 | 3 | public class PersonalRoaster implements Builder { 4 | 5 | private Roaster roaster = new Roaster(); 6 | 7 | @Override 8 | public void buildCoolingTray() { 9 | roaster.add("Personal Roaster Cooling Tray added"); 10 | } 11 | 12 | @Override 13 | public void buildExhaustSystem() { 14 | roaster.add("Personal Roaster Exhaust System added"); 15 | } 16 | 17 | @Override 18 | public void buildGasBurner() { 19 | roaster.add("Personal Roaster Gas Burner added"); 20 | } 21 | 22 | @Override 23 | public void buildPlatform() { 24 | // do nothing - not applicable for personal roasters 25 | } 26 | 27 | @Override 28 | public void buildMotor() { 29 | roaster.add("Standard Motor added"); 30 | } 31 | 32 | @Override 33 | public void buildThermocouples() { 34 | roaster.add("Standard Thermocouples added"); 35 | } 36 | 37 | @Override 38 | public void buildInnerDrum() { 39 | roaster.add("Personal Roaster Inner Drum added"); 40 | } 41 | 42 | @Override 43 | public void buildMainBody() { 44 | roaster.add("Personal Roaster Main body added"); 45 | } 46 | 47 | @Override 48 | public Roaster getRoaster() { 49 | return roaster; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Chapter04/CH4Builder/Roaster.java: -------------------------------------------------------------------------------- 1 | package CH4Builder; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class Roaster { 6 | 7 | private LinkedList components; 8 | 9 | public Roaster() { 10 | components = new LinkedList<>(); 11 | } 12 | 13 | public void add(String component) { 14 | components.addLast(component); 15 | } 16 | 17 | public void display() { 18 | System.out.println("\n\nROASTER BUILD:"); 19 | for (int i=0; i staffList; 11 | 12 | Chef(String name, String role) { 13 | this.name = name; 14 | this.role = role; 15 | staffList = new ArrayList(); 16 | } 17 | 18 | public void add(Chef chef) { 19 | staffList.add(chef); 20 | } 21 | 22 | public void fire(Chef chef) { 23 | staffList.remove(chef); 24 | } 25 | 26 | public List getStaffList() { 27 | return staffList; 28 | } 29 | 30 | @Override 31 | public String getDetails() { 32 | return (name + " is assigned the role of " + role); 33 | } 34 | 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | public String getRole() { 40 | return role; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter05/CH5Composite/KitchenStaff.java: -------------------------------------------------------------------------------- 1 | package CH5Composite; 2 | 3 | public interface KitchenStaff { 4 | 5 | public String getDetails(); 6 | } 7 | -------------------------------------------------------------------------------- /Chapter05/CH5Composite/KitchenStaffDriver.java: -------------------------------------------------------------------------------- 1 | package CH5Composite; 2 | 3 | import java.util.List; 4 | 5 | public class KitchenStaffDriver { 6 | 7 | public static void main(String[] args) { 8 | 9 | // create sample data 10 | Chef execChef = new Chef("Gemma Patron", "Executive Chef"); 11 | Chef headChef = new Chef("Tiksha Century", "Head Chef"); 12 | Chef sousChef1 = new Chef ("Tilly Hope", "Sous Chef"); 13 | Chef sousChef2 = new Chef ("Pat Stringe", "Sous Chef"); 14 | Chef lineChef1 = new Chef ("Seth Arpage", "Line Chef"); 15 | Chef lineChef2 = new Chef ("Diego Salazar", "Line Chef"); 16 | Chef lineChef3 = new Chef ("Cersei Butrix", "Line Chef"); 17 | Chef lineChef4 = new Chef ("Marissa Parth", "Line Chef"); 18 | Chef commisChef1 = new Chef ("Johnny Ferd", "Commis Chef"); 19 | Chef commisChef2 = new Chef ("Kay Fleping", "Commis Chef"); 20 | 21 | // establish Executive Chef at top of tree structure 22 | // make Head Chef subordinate to Executive Chef 23 | execChef.add(headChef); 24 | 25 | // subordinate Sous Chefs to Head Chef 26 | headChef.add(sousChef1); 27 | headChef.add(sousChef2); 28 | 29 | // subordinate Line Chefs to Sous Chefs 30 | sousChef1.add(lineChef1); 31 | sousChef1.add(lineChef2); 32 | sousChef1.add(lineChef3); 33 | sousChef1.add(lineChef4); 34 | 35 | // subordinate Commmis Chefs under Line Chef 1 36 | lineChef1.add(commisChef1); 37 | lineChef1.add(commisChef2); 38 | 39 | // no subordinates to other Line Chefs 40 | lineChef2.add(null); 41 | lineChef3.add(null); 42 | lineChef4.add(null); 43 | 44 | // no subordinates to Commis Chefs 45 | commisChef1.add(null); 46 | commisChef2.add(null); 47 | 48 | // provide console output 49 | System.out.println("\n\nKitchen Staff Management System\n"); 50 | System.out.println(execChef.getDetails()); 51 | 52 | List head = execChef.getStaffList(); 53 | for (int i=0; i < head.size(); i++) { 54 | System.out.println("\t" + head.get(i).getDetails()); 55 | } 56 | 57 | List sous = headChef.getStaffList(); 58 | for (int i=0; i < sous.size(); i++) { 59 | System.out.println("\t\t" + sous.get(i).getDetails()); 60 | } 61 | 62 | List line = sousChef1.getStaffList(); 63 | for (int i=0; i < line.size(); i++) { 64 | System.out.println("\t\t\t" + line.get(i).getDetails()); 65 | } 66 | 67 | List commis = lineChef1.getStaffList(); 68 | for (int i=0; i < commis.size(); i++) { 69 | System.out.println("\t\t\t\t" + commis.get(i).getDetails()); 70 | } 71 | 72 | // firing a line chef 73 | System.out.println("\n\nKITCHEN STAFF UPDATE"); 74 | System.out.println("\t" + lineChef1.getName() + 75 | ", " + lineChef1.getRole() + ", has been terminated."); 76 | sousChef1.fire(lineChef1); 77 | System.out.println("\nHere is the updated list of Line Chefs:"); 78 | List newLine = sousChef1.getStaffList(); 79 | for (int i=0; i < newLine.size(); i++) { 80 | System.out.println("\t" + newLine.get(i).getDetails()); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Chapter05/CH5Decorator/AbstractDecorator.java: -------------------------------------------------------------------------------- 1 | package CH5Decorator; 2 | 3 | abstract class AbstractDecorator extends Printer { 4 | 5 | protected Printer printer; 6 | 7 | public void selectPrinterToFlush(Printer ptr) { 8 | printer = ptr; 9 | } 10 | 11 | public void flushBuffer() { 12 | if (printer != null) { 13 | printer.flushBuffer(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Chapter05/CH5Decorator/ConcreteDecorator1.java: -------------------------------------------------------------------------------- 1 | package CH5Decorator; 2 | 3 | public class ConcreteDecorator1 extends AbstractDecorator { 4 | 5 | public void flushBuffer() { 6 | super.flushBuffer(); 7 | System.out.println("Message from Concrete Decorator 1: " + 8 | "Printer Buffer Flushed"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter05/CH5Decorator/ConcreteDecorator2.java: -------------------------------------------------------------------------------- 1 | package CH5Decorator; 2 | 3 | public class ConcreteDecorator2 extends AbstractDecorator { 4 | 5 | public void flushBuffer() { 6 | 7 | System.out.println("\n[ START ] Concrete Decorator 2 Wrapper [ START ]"); 8 | super.flushBuffer(); 9 | 10 | System.out.println("Message from Concrete Decorator 2: " + 11 | "Printer Buffer Flushed"); 12 | System.out.println("[ END ] Concrete Decorator 2 Wrapper [ END ]"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter05/CH5Decorator/ConcretePrinter.java: -------------------------------------------------------------------------------- 1 | package CH5Decorator; 2 | 3 | public class ConcretePrinter extends Printer { 4 | 5 | @Override 6 | public void flushBuffer() { 7 | System.out.println("Message from Concrete Printer: Printer Buffer Flushed"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Chapter05/CH5Decorator/DecoratorDriver.java: -------------------------------------------------------------------------------- 1 | package CH5Decorator; 2 | 3 | public class DecoratorDriver { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("\n\n======================================================"); 8 | System.out.println("\t\t\tPrinter Buffer Flusher Demo"); 9 | System.out.println("======================================================"); 10 | ConcretePrinter concreteFlush = new ConcretePrinter(); 11 | 12 | // create concrete decorator 13 | ConcreteDecorator1 cd1 = new ConcreteDecorator1(); 14 | // decorate cd1 15 | cd1.selectPrinterToFlush(concreteFlush); 16 | cd1.flushBuffer(); 17 | 18 | // create concrete decorator 19 | ConcreteDecorator2 cd2 = new ConcreteDecorator2(); 20 | // decorate cd2 21 | cd2.selectPrinterToFlush(cd1); 22 | cd2.flushBuffer(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter05/CH5Decorator/Printer.java: -------------------------------------------------------------------------------- 1 | package CH5Decorator; 2 | 3 | abstract class Printer { 4 | public abstract void flushBuffer(); 5 | } 6 | -------------------------------------------------------------------------------- /Chapter05/CH5Facade/FacadeDriver.java: -------------------------------------------------------------------------------- 1 | package CH5Facade; 2 | 3 | import CH5Facade.MealFacade.MealFacade; 4 | 5 | public class FacadeDriver { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.println("\n\n======================================================"); 10 | System.out.println("\t\t\tMeal Assembly Service Demo"); 11 | System.out.println("======================================================"); 12 | 13 | // assemble three meals 14 | MealFacade meal1 = new MealFacade(); 15 | meal1.assembleMeal("Steak", "Asparagus", "Wild Rice"); 16 | 17 | MealFacade meal2 = new MealFacade(); 18 | meal2.assembleMeal("Chicken", "Green Beans", "Potato Wedges"); 19 | 20 | MealFacade meal3 = new MealFacade(); 21 | meal3.assembleMeal("Meatloaf", "Brussel Sprouts", "Mashed Potatoes"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter05/CH5Facade/MealComponents/MealProtein.java: -------------------------------------------------------------------------------- 1 | package CH5Facade.MealComponents; 2 | 3 | public class MealProtein { 4 | 5 | private String protein; 6 | 7 | public void setProtein(String protein) { 8 | this.protein = protein; 9 | System.out.println("\t\tProtein (" + this.protein + ") added to meal."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/CH5Facade/MealComponents/MealStarch.java: -------------------------------------------------------------------------------- 1 | package CH5Facade.MealComponents; 2 | 3 | public class MealStarch { 4 | 5 | private String starch; 6 | 7 | public void setStarch(String starch) { 8 | this.starch = starch; 9 | System.out.println("\t\tStarch (" + this.starch + ") added to meal."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/CH5Facade/MealComponents/MealVegetable.java: -------------------------------------------------------------------------------- 1 | package CH5Facade.MealComponents; 2 | 3 | public class MealVegetable { 4 | 5 | private String vegetable; 6 | 7 | public void setVegetable(String vegetable) { 8 | this.vegetable = vegetable; 9 | System.out.println("\t\tVegetable (" + this.vegetable + ") added to meal."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/CH5Facade/MealFacade/MealFacade.java: -------------------------------------------------------------------------------- 1 | package CH5Facade.MealFacade; 2 | 3 | import CH5Facade.MealComponents.MealProtein; 4 | import CH5Facade.MealComponents.MealVegetable; 5 | import CH5Facade.MealComponents.MealStarch; 6 | 7 | public class MealFacade { 8 | 9 | MealProtein newProtein; 10 | MealVegetable newVegetable; 11 | MealStarch newStarch; 12 | 13 | public MealFacade() { 14 | newProtein = new MealProtein(); 15 | newVegetable = new MealVegetable(); 16 | newStarch = new MealStarch(); 17 | } 18 | 19 | public void assembleMeal(String protein, String vegetable, String starch) { 20 | 21 | System.out.println("\n\tMeal assembly process initiated. . . "); 22 | newProtein.setProtein(protein); 23 | newVegetable.setVegetable(vegetable); 24 | newStarch.setStarch(starch); 25 | System.out.println("\tMeal assembly process completed. . . \n"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Chapter05/CH5Flyweight/Mattress.java: -------------------------------------------------------------------------------- 1 | package CH5Flyweight; 2 | 3 | public class Mattress implements MattressInterface { 4 | 5 | // class variables 6 | String matrressSize; 7 | public String mattressFirmness; 8 | 9 | // constructor 10 | public Mattress(String matrressSize) { 11 | this.matrressSize = matrressSize; 12 | } 13 | 14 | // mutator 15 | public void setMattressFirmness(String mattressFirmness) { 16 | this.mattressFirmness = mattressFirmness; 17 | } 18 | 19 | @Override 20 | public void print() { 21 | System.out.println("\t\tThis is a " + mattressFirmness + 22 | " " + matrressSize + " mattress."); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Chapter05/CH5Flyweight/MattressDriver.java: -------------------------------------------------------------------------------- 1 | package CH5Flyweight; 2 | 3 | public class MattressDriver { 4 | 5 | public static void main(String[] args) throws Exception { 6 | 7 | MattressFactory theFactory = new MattressFactory(); 8 | 9 | System.out.println("\n\n======================================================"); 10 | System.out.println("\t\t\tMattress Manufacturing Factory Demo"); 11 | System.out.println("======================================================"); 12 | 13 | Mattress newMattress; 14 | 15 | for (int i = 0; i < 5; i++) { 16 | newMattress = (Mattress)theFactory.getFactoryMattress("Crib"); 17 | newMattress.setMattressFirmness("Firm"); 18 | newMattress.print(); 19 | } 20 | 21 | for (int i = 0; i < 5; i++) { 22 | newMattress = (Mattress)theFactory.getFactoryMattress("Twin"); 23 | newMattress.setMattressFirmness("Soft"); 24 | newMattress.print(); 25 | } 26 | 27 | for (int i = 0; i < 5; i++) { 28 | newMattress = (Mattress)theFactory.getFactoryMattress("Full"); 29 | newMattress.setMattressFirmness("Extra Firm"); 30 | newMattress.print(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Chapter05/CH5Flyweight/MattressFactory.java: -------------------------------------------------------------------------------- 1 | package CH5Flyweight; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class MattressFactory { 7 | 8 | Map sizes = new HashMap(); 9 | 10 | public int numberOfMattresses() { 11 | return sizes.size(); 12 | } 13 | 14 | public MattressInterface getFactoryMattress(String mSize) throws Exception { 15 | MattressInterface mattressSize = null; 16 | if (sizes.containsKey(mSize)) { 17 | mattressSize = sizes.get(mSize); 18 | } else { 19 | switch (mSize) { 20 | case "Crib": 21 | System.out.println("\tA Crib Mattress did not exist, but does now"); 22 | mattressSize = new Mattress("Crib"); 23 | sizes.put("Crib", mattressSize); 24 | break; 25 | 26 | case "Twin": 27 | System.out.println("\tA Twin Mattress did not exist, but does now"); 28 | mattressSize = new Mattress("Twin"); 29 | sizes.put("Twin", mattressSize); 30 | break; 31 | 32 | case "Full": 33 | System.out.println("\tA Full Mattress did not exist, but does now"); 34 | mattressSize = new Mattress("Full"); 35 | sizes.put("Full", mattressSize); 36 | break; 37 | 38 | default: 39 | throw new Exception("\tMattress Creation Request Error: " + 40 | "invalid mattress size defined."); 41 | } 42 | } 43 | return mattressSize; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Chapter05/CH5Flyweight/MattressInterface.java: -------------------------------------------------------------------------------- 1 | package CH5Flyweight; 2 | 3 | public interface MattressInterface { 4 | 5 | void print(); 6 | } 7 | -------------------------------------------------------------------------------- /Chapter05/CH5Proxy/MasterClasses/ConcreteWeather.java: -------------------------------------------------------------------------------- 1 | package CH5Proxy.MasterClasses; 2 | 3 | public class ConcreteWeather extends Weather { 4 | 5 | @Override 6 | public void whoAmI() { 7 | System.out.println("\tMethod Call from " + 8 | this.getClass().getSimpleName() + " class"); 9 | System.out.println("\t\tWeather forcast is sunny\n"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/CH5Proxy/MasterClasses/Weather.java: -------------------------------------------------------------------------------- 1 | package CH5Proxy.MasterClasses; 2 | 3 | public abstract class Weather { 4 | 5 | public abstract void whoAmI(); 6 | } 7 | -------------------------------------------------------------------------------- /Chapter05/CH5Proxy/ProxyClasses/Proxy.java: -------------------------------------------------------------------------------- 1 | package CH5Proxy.ProxyClasses; 2 | 3 | import CH5Proxy.MasterClasses.ConcreteWeather; 4 | import CH5Proxy.MasterClasses.Weather; 5 | 6 | public class Proxy extends Weather { 7 | 8 | ConcreteWeather concreteWeather; 9 | 10 | @Override 11 | public void whoAmI() { 12 | System.out.println("\tMethod Call from " + 13 | this.getClass().getSimpleName() + " class"); 14 | System.out.println("\t\tWeather forcast is overcast and rain\n"); 15 | if (concreteWeather == null) { 16 | concreteWeather = new ConcreteWeather(); 17 | } 18 | concreteWeather.whoAmI(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Chapter05/CH5Proxy/ProxyClasses/ProxyDriver.java: -------------------------------------------------------------------------------- 1 | package CH5Proxy.ProxyClasses; 2 | 3 | public class ProxyDriver { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("\n\n======================================================"); 8 | System.out.println("\t\t\tProxy Weather Forecast Demo"); 9 | System.out.println("======================================================"); 10 | 11 | Proxy proxyCall = new Proxy(); 12 | proxyCall.whoAmI(); 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter07/CH7MVC/Book.java: -------------------------------------------------------------------------------- 1 | package CH7MVC; 2 | 3 | public class Book { 4 | 5 | private String isbn; 6 | private String title; 7 | private int year; 8 | 9 | 10 | // accessor methods 11 | public String getISBN() { 12 | return isbn; 13 | } 14 | 15 | public String getTitle() { 16 | return title; 17 | } 18 | 19 | public int getYear() { 20 | return year; 21 | } 22 | 23 | 24 | // mutator methods 25 | public void setISBN(String isbn) { 26 | this.isbn = isbn; 27 | } 28 | 29 | public void setTitle(String title) { 30 | this.title = title; 31 | } 32 | 33 | public void setYear(int year) { 34 | this.year = year; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Chapter07/CH7MVC/BookController.java: -------------------------------------------------------------------------------- 1 | package CH7MVC; 2 | 3 | public class BookController { 4 | private Book model; 5 | private BookView view; 6 | 7 | // constructor 8 | public BookController(Book model, BookView view) { 9 | this.model = model; 10 | this.view = view; 11 | } 12 | 13 | // accessor methods 14 | public String getBookTitle() { 15 | return model.getTitle(); 16 | } 17 | 18 | public String getBookISBN() { 19 | return model.getISBN(); 20 | } 21 | 22 | public int getBookYear() { 23 | return model.getYear(); 24 | } 25 | 26 | // mutator methods 27 | public void setBookTitle(String title) { 28 | model.setTitle(title); 29 | } 30 | 31 | public void setBookISBN(String isbn) { 32 | model.setISBN(isbn); 33 | } 34 | 35 | public void setBookYear(int year) { 36 | model.setYear(year); 37 | } 38 | 39 | // update view method 40 | public void updateView() { 41 | view.printBookData(model.getTitle(), model.getISBN(), model.getYear()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Chapter07/CH7MVC/BookView.java: -------------------------------------------------------------------------------- 1 | package CH7MVC; 2 | 3 | public class BookView { 4 | 5 | public void printBookData(String bookTitle, String bookISBN, int bookYear) { 6 | System.out.println("\nBook Title : " + bookTitle); 7 | System.out.println("ISBN-13 : " + bookISBN); 8 | System.out.println("Pub. Year : " + bookYear + "\n"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter07/CH7MVC/MVCArchitecturalPattern.java: -------------------------------------------------------------------------------- 1 | package CH7MVC; 2 | 3 | public class MVCArchitecturalPattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | Book model = pullBookDetails(); 8 | 9 | BookView view = new BookView(); 10 | 11 | BookController con = new BookController(model, view); 12 | 13 | con.updateView(); 14 | 15 | con.setBookTitle("Mastering Java 11"); 16 | con.setBookISBN("978-1789137613"); 17 | con.setBookYear(2018); 18 | con.updateView(); 19 | } 20 | 21 | private static Book pullBookDetails() { 22 | Book book = new Book(); 23 | book.setTitle("Mastering Java 9"); 24 | book.setISBN("978-1786468734"); 25 | book.setYear(2017); 26 | return book; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter08/CH8Fibonacci1/FibonacciTest1.java: -------------------------------------------------------------------------------- 1 | package CH8Fibonacci1; 2 | 3 | public class FibonacciTest1 { 4 | 5 | public static int computeFibonacciNumber(int number) { 6 | 7 | // this checks for the fibonacci base of 0 and 1 8 | if ( (number == 0) || ( number == 1) ) { 9 | return number; 10 | } 11 | 12 | System.out.println("Computing computeFibonacciNumber(int " + number + ")..."); 13 | 14 | return (computeFibonacciNumber(number - 1)) + (computeFibonacciNumber(number - 2)); 15 | } 16 | 17 | public static void main(String[] args) { 18 | 19 | System.out.println(); 20 | computeFibonacciNumber(30); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter08/CH8Fibonacci2/FibonacciTest2.java: -------------------------------------------------------------------------------- 1 | package CH8Fibonacci2; 2 | 3 | import java.util.Map; 4 | import java.util.HashMap; 5 | 6 | class FibonacciTest2 { 7 | 8 | private static Map memoization = new HashMap<>(); 9 | 10 | public static int computeFibonacciNumber(int number) { 11 | 12 | // this checks for the fibonacci base of 0 and 1 13 | if ( (number == 0) || ( number == 1) ) { 14 | return number; 15 | } 16 | 17 | // Step 1: Check if calculation has already been made 18 | if (memoization.containsKey(number)) { 19 | System.out.println("First time computing memoization " + number); 20 | return memoization.get(number); 21 | } 22 | 23 | // Step 2: Calculate if not already calculated 24 | System.out.println("Computing computeFibonacciNumber(int " + number + ")..."); 25 | int fibonacciResult = (computeFibonacciNumber(number - 1)) + (computeFibonacciNumber(number - 2)); 26 | 27 | // Step 3: Add result to Map 28 | memoization.put(number, fibonacciResult); 29 | 30 | return fibonacciResult; 31 | } 32 | 33 | public static void main(String[] args) { 34 | 35 | System.out.println(); 36 | computeFibonacciNumber(7); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter08/CH8Lambda1/Driver.java: -------------------------------------------------------------------------------- 1 | package CH8Lambda1; 2 | 3 | public class Driver { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println(); 8 | FunctionalGift myObject = (int number)->System.out.println 9 | (number + " squared is " + (number*number)); 10 | 11 | myObject.abstractMethod(1); 12 | myObject.abstractMethod(2); 13 | myObject.abstractMethod(3); 14 | myObject.abstractMethod(4); 15 | myObject.abstractMethod(5); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter08/CH8Lambda1/FunctionalGift.java: -------------------------------------------------------------------------------- 1 | package CH8Lambda1; 2 | 3 | public interface FunctionalGift { 4 | 5 | void abstractMethod(int number); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /Chapter08/CH8Lambda2/Driver.java: -------------------------------------------------------------------------------- 1 | package CH8Lambda2; 2 | 3 | import java.util.Random; 4 | import java.util.Scanner; 5 | 6 | public class Driver { 7 | 8 | interface FirstFunctionalInterface { 9 | int calculation(int a, int b); 10 | } 11 | 12 | interface SecondFunctionalInterface { 13 | void displayResults(String message); 14 | } 15 | 16 | private int calculate(int a, int b, FirstFunctionalInterface firstObject) { 17 | return firstObject.calculation(a, b); 18 | } 19 | 20 | public static void main(String[] args) { 21 | 22 | // Obtain user input 23 | System.out.println(); 24 | Scanner in = new Scanner(System.in); 25 | System.out.println("How many blue tokens do you have to exchange: "); 26 | int blueTokens = in.nextInt(); 27 | System.out.println("How many red tokens do you have to exchange: "); 28 | int redTokens = in.nextInt(); 29 | 30 | // Display system header 31 | System.out.println("\n======================"); 32 | System.out.println("TOKEN-TO-GIFT EXCHANGE"); 33 | System.out.println("======================"); 34 | 35 | // add blue and red tokens 36 | FirstFunctionalInterface sum = (int nbr1, int nbr2) -> nbr1 + nbr2; 37 | 38 | FirstFunctionalInterface superSquare = (int nbr1, int nbr2) -> 39 | ((nbr1 * nbr1) + (nbr2 * nbr2)); 40 | 41 | Driver firstObject = new Driver(); 42 | 43 | // Generate output 44 | System.out.println(blueTokens + " blue tokens submitted"); 45 | System.out.println(redTokens + " red tokens submitted"); 46 | System.out.println(firstObject.calculate(blueTokens, redTokens, sum) + 47 | " total tokens submitted"); 48 | 49 | System.out.println(firstObject.calculate(blueTokens, redTokens, superSquare) + 50 | " SuperSquare number result"); 51 | 52 | System.out.println("=="); 53 | SecondFunctionalInterface secondObject = message -> 54 | System.out.println("Your gift is a pound of " + message); 55 | 56 | secondObject.displayResults(selectGift()); 57 | } 58 | 59 | public static String selectGift() { 60 | String[] giftArray = new String[] 61 | {"Gold", "Silver", "Platinum", "Titanium", "Copper"}; 62 | Random giftNumber = new Random(); 63 | int giftToGive = giftNumber.nextInt(4); 64 | 65 | return giftArray[giftToGive]; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Chapter08/CH8Lambda2/FunctionalGift.java: -------------------------------------------------------------------------------- 1 | package CH8Lambda2; 2 | 3 | public interface FunctionalGift { 4 | 5 | void abstractMethod(int number); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /Chapter08/CH8Loan1/Driver.java: -------------------------------------------------------------------------------- 1 | package CH8Loan1; 2 | 3 | public class Driver { 4 | 5 | public static void main(String[] args) { 6 | FileToProcess myFile = new FileToProcess(); 7 | 8 | myFile.openFile().processMetaData().analyzeHeader() 9 | .checkSpelling().checkGrammar().closeFile(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter08/CH8Loan1/FileToProcess.java: -------------------------------------------------------------------------------- 1 | package CH8Loan1; 2 | 3 | public class FileToProcess { 4 | 5 | // constructor 6 | public FileToProcess() { 7 | } 8 | 9 | public FileToProcess openFile() { 10 | System.out.println("\nFile opened for processing"); 11 | return this; 12 | } 13 | 14 | public FileToProcess processMetaData() { 15 | System.out.println("\tProcessing metadata. . ."); 16 | return this; 17 | } 18 | 19 | public FileToProcess analyzeHeader() { 20 | System.out.println ("\tAnalyzing header. . ."); 21 | return this; 22 | } 23 | 24 | public FileToProcess checkSpelling() { 25 | System.out.println("\tChecking spelling. . . "); 26 | return this; 27 | } 28 | 29 | public FileToProcess checkGrammar() { 30 | System.out.println("\tChecking grammar. . . "); 31 | return this; 32 | } 33 | 34 | public void closeFile() { 35 | System.out.println("File closed"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter08/CH8Loan2/Driver2.java: -------------------------------------------------------------------------------- 1 | package CH8Loan2; 2 | 3 | public class Driver2 { 4 | 5 | public static void main(String[] args) { 6 | 7 | FileToProcess2.processFile(theFile -> theFile.processMetaData() 8 | .analyzeHeader().checkSpelling().checkGrammar()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter08/CH8Loan2/FileToProcess2.java: -------------------------------------------------------------------------------- 1 | package CH8Loan2; 2 | 3 | import java.util.function.Consumer; 4 | 5 | public class FileToProcess2 { 6 | 7 | // constructor 8 | protected FileToProcess2() { 9 | openFile(); 10 | } 11 | 12 | public static void processFile(final Consumer block) { 13 | final FileToProcess2 theFile = new FileToProcess2(); 14 | 15 | block.accept(theFile); 16 | 17 | theFile.closeFile(); 18 | } 19 | 20 | 21 | public FileToProcess2 openFile() { 22 | System.out.println("\nFile opened for processing by constructor"); 23 | return this; 24 | } 25 | 26 | public FileToProcess2 processMetaData() { 27 | System.out.println("\tProcessing metadata. . ."); 28 | return this; 29 | } 30 | 31 | public FileToProcess2 analyzeHeader() { 32 | System.out.println ("\tAnalyzing header. . ."); 33 | return this; 34 | } 35 | 36 | public FileToProcess2 checkSpelling() { 37 | System.out.println("\tChecking spelling. . . "); 38 | return this; 39 | } 40 | 41 | public FileToProcess2 checkGrammar() { 42 | System.out.println("\tChecking grammar. . . "); 43 | return this; 44 | } 45 | 46 | public void closeFile() { 47 | System.out.println("File closed"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Chapter08/CH8Stream/StreamExample.java: -------------------------------------------------------------------------------- 1 | package CH8Stream; 2 | 3 | import java.util.stream.Stream; 4 | 5 | public class StreamExample { 6 | 7 | public static void main(String[] args) { 8 | 9 | System.out.println(); 10 | 11 | Stream.iterate(0, x->x+3) 12 | .peek(number -> System.out.print("\nPeeked at: ")) 13 | .limit(7) 14 | .forEach(System.out::println); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Chapter08/CH8TailCall/TailCallExample.java: -------------------------------------------------------------------------------- 1 | package CH8TailCall; 2 | 3 | import java.util.Scanner; 4 | 5 | public class TailCallExample { 6 | 7 | public static int theInitialNumber; 8 | 9 | public static void main(String[] args) { 10 | 11 | Scanner in = new Scanner(System.in); 12 | System.out.println("\n\nI can turn your number into 7."); 13 | System.out.print("Enter a number: "); 14 | theInitialNumber = in.nextInt(); 15 | 16 | // Display system header 17 | System.out.println("\n========================="); 18 | System.out.println("ANY NUMBER CAN BE LUCKY 7"); 19 | System.out.println("========================="); 20 | 21 | System.out.println("\nThe intial number: " + theInitialNumber); 22 | 23 | System.out.println("The tail call sent this as the result: " + 24 | (excecuteThisMethod(theInitialNumber))); // tail call 25 | } 26 | 27 | private static int excecuteThisMethod(int theNumber) { 28 | 29 | int funWithNumbers; 30 | 31 | funWithNumbers = operation1(theNumber); 32 | 33 | funWithNumbers = operation2(funWithNumbers); 34 | 35 | funWithNumbers = operation3(funWithNumbers); 36 | 37 | funWithNumbers = operation4(funWithNumbers); 38 | 39 | funWithNumbers = operation5(funWithNumbers); // tail call 40 | 41 | return(funWithNumbers); 42 | } 43 | 44 | private static int operation1(int theNbr) { 45 | System.out.println("\t+ 9 = " + (theNbr + 9)); // tail call 46 | return theNbr + 9; 47 | } 48 | private static int operation2(int theNbr) { 49 | System.out.println("\t* 2 = " + (theNbr * 2)); // tail call 50 | return theNbr * 2; 51 | } 52 | private static int operation3(int theNbr) { 53 | System.out.println("\t- 4 = " + (theNbr - 4)); // tail call 54 | return theNbr - 4; 55 | } 56 | private static int operation4(int theNbr) { 57 | System.out.println("\t/ 2 = " + (theNbr / 2)); // tail call 58 | return theNbr / 2; 59 | } 60 | private static int operation5(int theNbr) { 61 | System.out.println("\t- initial number = " + (theNbr - theInitialNumber)); // tail call 62 | return (theNbr - theInitialNumber); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Chapter09/CH9AsynchronousCommunication/CallbackListener.java: -------------------------------------------------------------------------------- 1 | package CH9AsynchronousCommunication; 2 | 3 | public interface CallbackListener { 4 | 5 | void processCallback(); 6 | } 7 | 8 | -------------------------------------------------------------------------------- /Chapter09/CH9AsynchronousCommunication/CallerOne.java: -------------------------------------------------------------------------------- 1 | package CH9AsynchronousCommunication; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.ListIterator; 7 | 8 | public class CallerOne implements CallbackListener { 9 | 10 | @Override 11 | public void processCallback() 12 | { 13 | System.out.println("\nAsynchronous Task Completed Followed by Callback."); 14 | 15 | System.out.println("\tSimulated processing from Caller One . . . "); 16 | doSomething1(34, 12); 17 | 18 | System.out.println("\tSimulated processing from Caller Two . . . "); 19 | doSomething2("nrettaP ngiseD noitacinummoC suonorhcnysA"); 20 | System.out.println(); 21 | } 22 | 23 | public void doSomething1(int x, int y) { 24 | 25 | // determine and output max value 26 | System.out.println("\t\tThe largest number is " + Math.max(x, y)); 27 | } 28 | 29 | public void doSomething2(String backwardsPhrase) { 30 | 31 | // reverse a string 32 | char[] phrase = backwardsPhrase.toCharArray(); 33 | List newPhrase = new ArrayList<>(); 34 | 35 | for (char character: phrase) 36 | newPhrase.add(character); 37 | 38 | Collections.reverse(newPhrase); 39 | ListIterator myInterator = newPhrase.listIterator(); 40 | 41 | System.out.print("\t\tResultant Phrase: "); 42 | while (myInterator.hasNext()) 43 | System.out.print(myInterator.next()); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Chapter09/CH9AsynchronousCommunication/CallerTwo.java: -------------------------------------------------------------------------------- 1 | package CH9AsynchronousCommunication; 2 | 3 | public class CallerTwo { 4 | 5 | // create callbackListener object 6 | private CallbackListener callbackListener; 7 | 8 | // setting up the callbacklistener 9 | public void registerCallbackListener(CallbackListener callbackListener) 10 | { 11 | this.callbackListener = callbackListener; 12 | } 13 | 14 | // asynchronous operation for CallerTwo 15 | public void processCallback() 16 | { 17 | // a new thread for the asynchronous operations using lambda 18 | new Thread(() -> { 19 | // simulated processing 20 | System.out.println("\nAsynchronous operations taking place . . ."); 21 | System.out.println("\tSimulated processing from Caller Two. . . "); 22 | 23 | // check if callbackListener exists 24 | if (callbackListener != null) { 25 | 26 | // use processCallback() method of CallerOne 27 | callbackListener.processCallback(); 28 | } 29 | }).start(); 30 | } 31 | 32 | public static void main(String[] args) 33 | { 34 | CallerTwo asynchronousMessage = new CallerTwo(); // line 1 35 | 36 | CallbackListener callbackListener = new CallerOne(); // line 2 37 | 38 | asynchronousMessage.registerCallbackListener(callbackListener); // line 3 39 | 40 | asynchronousMessage.processCallback(); // line 4 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Chapter09/CH9BoundedQueue/Bounded.java: -------------------------------------------------------------------------------- 1 | package CH9BoundedQueue; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | 5 | public class Bounded extends Thread { 6 | 7 | private BlockingQueue inputValue; 8 | 9 | Bounded(BlockingQueue blockingQueue) { 10 | this.inputValue = blockingQueue; 11 | } 12 | 13 | public void run() { 14 | try { 15 | while (true) { 16 | Integer myInteger = inputValue.take(); 17 | 18 | if (myInteger == null) { 19 | break; 20 | } 21 | System.out.println(myInteger + " squared is " + 22 | (myInteger * myInteger)); 23 | } 24 | } catch (InterruptedException e) { 25 | System.out.println("Interrupted Exception Encountered."); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter09/CH9BoundedQueue/Driver.java: -------------------------------------------------------------------------------- 1 | package CH9BoundedQueue; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.BlockingQueue; 5 | 6 | public class Driver { 7 | 8 | public static void main(String[] args) throws InterruptedException { 9 | 10 | int boundedSize = 10; 11 | 12 | BlockingQueue blockingQueue = new ArrayBlockingQueue<>(boundedSize); 13 | 14 | int boundedThread = 2; 15 | 16 | Bounded[] bounded = new Bounded[boundedThread]; 17 | 18 | System.out.println(); 19 | 20 | for (int i=0; i < bounded.length; i++) { 21 | bounded[i] = new Bounded(blockingQueue); 22 | bounded[i].start(); 23 | } 24 | 25 | for (int i=1; i < 11; i++) { 26 | blockingQueue.put(i); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Chapter09/CH9Caching/CacheDriver.java: -------------------------------------------------------------------------------- 1 | package CH9Caching; 2 | 3 | public class CacheDriver { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("\nChapter 9 Caching System."); 8 | 9 | ExampleCache myCache = new ExampleCache(5); 10 | 11 | myCache.put(8, 33643); // K.Bryant 12 | myCache.put(14, 25192); // J.West 13 | myCache.put(22, 23149); // E.Baylor 14 | myCache.put(24, 33643); // K.Bryant 15 | myCache.put(32, 17707); // E.Johnson 16 | myCache.put(33, 24176); // K.Jabbar 17 | 18 | System.out.println("From Cache Driver: Jersey-> 8\tPoints-> " + myCache.retrieve(8)); 19 | System.out.println("From Cache Driver: Jersey-> 14\tPoints-> " + myCache.retrieve(14)); 20 | System.out.println("From Cache Driver: Jersey-> 22\tPoints-> " + myCache.retrieve(22)); 21 | System.out.println("From Cache Driver: Jersey-> 24\tPoints-> " + myCache.retrieve(24)); 22 | System.out.println("From Cache Driver: Jersey-> 32\tPoints-> " + myCache.retrieve(32)); 23 | System.out.println("From Cache Driver: Jersey-> 33\tPoints-> " + myCache.retrieve(33)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Chapter09/CH9Caching/ExampleCache.java: -------------------------------------------------------------------------------- 1 | package CH9Caching; 2 | 3 | import java.util.HashMap; 4 | 5 | public class ExampleCache { 6 | 7 | // class variables 8 | private HashMap map; 9 | private int cacheCapacity; 10 | private int cacheCount; 11 | private Player playerHead; 12 | private Player playerTail; 13 | 14 | // constructor 15 | public ExampleCache(int cCapacity) { 16 | this.cacheCapacity = cCapacity; 17 | 18 | map = new HashMap<>(); 19 | playerHead = new Player(0,0); 20 | playerTail = new Player(0,0); 21 | playerHead.next = playerTail; 22 | playerTail.before = playerHead; 23 | playerHead.before = null; 24 | playerTail.next = null; 25 | cacheCount = 0; 26 | } 27 | 28 | public void addToPlayerHead(Player player) { 29 | player.next = playerHead.next; 30 | player.next.before = player; 31 | player.before = playerHead; 32 | playerHead.next = player; 33 | } 34 | 35 | public void deletePlayer(Player player) { 36 | player.before.next = player.next; 37 | player.next.before = player.before; 38 | } 39 | 40 | public int retrieve(int playerJersey) { 41 | if (map.get(playerJersey) != null) { 42 | Player player = map.get(playerJersey); 43 | int result = player.playerPoints; 44 | deletePlayer(player); 45 | addToPlayerHead(player); 46 | System.out.println("\t\t\t\t\t\t\t\t\tRETRIEVED: jersey -> " + playerJersey + 47 | "\tPoints-> " + result); 48 | return result; 49 | } 50 | System.out.println("\t\t\t\t\t\t\t\t\tRETRIEVED: jersey-> " + playerJersey + 51 | "\tPoints-> " + " no value"); 52 | return -1; 53 | } 54 | 55 | public void put(int jersey, int points) { 56 | System.out.println("SETTING: " + jersey + " (jersey) & " + 57 | points + " (points)"); 58 | if (map.get(jersey) != null) { 59 | Player player = map.get(jersey); 60 | player.playerPoints = points; 61 | deletePlayer(player); 62 | addToPlayerHead(player); 63 | } else { 64 | Player player = new Player(jersey, points); 65 | map.put(jersey, player); 66 | if (cacheCount < cacheCapacity) { 67 | cacheCount++; 68 | addToPlayerHead(player); 69 | } else { 70 | map.remove(playerTail.before.playerJersey); 71 | deletePlayer(playerTail.before); 72 | addToPlayerHead(player); 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Chapter09/CH9Caching/Player.java: -------------------------------------------------------------------------------- 1 | package CH9Caching; 2 | 3 | public class Player { 4 | 5 | int playerJersey; 6 | int playerPoints; 7 | Player before; 8 | Player next; 9 | 10 | // constructor 11 | public Player(int jersey, int points) { 12 | this.playerJersey = jersey; 13 | this.playerPoints = points; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter09/CH9FailFast/FailFastImplementation.java: -------------------------------------------------------------------------------- 1 | package CH9FailFast; 2 | 3 | import java.util.ConcurrentModificationException; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.Map; 7 | 8 | public class FailFastImplementation { 9 | 10 | public static void main(String[] args) throws ConcurrentModificationException { 11 | 12 | System.out.println(); 13 | 14 | Map firstLast = new HashMap(); 15 | firstLast.put("Kay", "Brentwood"); 16 | firstLast.put("Daisy", "Jinsen"); 17 | firstLast.put("Frank", "Corsack"); 18 | firstLast.put("Hugo", "Trapleton"); 19 | 20 | Iterator iterator = firstLast.keySet().iterator(); 21 | 22 | while (iterator.hasNext()) { 23 | 24 | try { 25 | System.out.println(firstLast.get(iterator.next())); 26 | } catch (ConcurrentModificationException e) { 27 | System.out.println("Encountered Exception: Failing Fast!"); 28 | return; 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Chapter09/CH9FailFast/FailFastImplementation2.java: -------------------------------------------------------------------------------- 1 | package CH9FailFast; 2 | 3 | import java.util.ConcurrentModificationException; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.Map; 7 | 8 | public class FailFastImplementation2 { 9 | 10 | public static void main(String[] args) throws ConcurrentModificationException { 11 | 12 | System.out.println(); 13 | 14 | Map firstLast = new HashMap(); 15 | firstLast.put("Kay", "Brentwood"); 16 | firstLast.put("Daisy", "Jinsen"); 17 | firstLast.put("Frank", "Corsack"); 18 | firstLast.put("Hugo", "Trapleton"); 19 | 20 | Iterator iterator = firstLast.keySet().iterator(); 21 | 22 | while (iterator.hasNext()) { 23 | 24 | try { 25 | System.out.println(firstLast.get(iterator.next())); 26 | } catch (ConcurrentModificationException e) { 27 | System.out.println("Encountered Exception: Failing Fast!"); 28 | return; 29 | } 30 | firstLast.put("Ingrid", "Lithingson"); 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /Chapter09/CH9FailureHandling/ControlledFailure.java: -------------------------------------------------------------------------------- 1 | package CH9FailureHandling; 2 | 3 | public class ControlledFailure { 4 | 5 | static int checkStatus(String component, int port){ 6 | 7 | System.out.println("\n\tChecking status of : " + component); 8 | // artifical introduction of divide by zero error 9 | int result = (port / 0); 10 | 11 | return result; 12 | } 13 | 14 | static int processServiceOrder(String process, int serviceOrderNbr) { 15 | 16 | int gatewayStatus = 0; 17 | 18 | try 19 | { 20 | gatewayStatus = checkStatus(process, serviceOrderNbr); 21 | } 22 | catch(NumberFormatException ex) 23 | { 24 | System.out.println("Error detected: " + ex.getMessage()); 25 | } 26 | return gatewayStatus; 27 | } 28 | 29 | public static void main(String args[]){ 30 | 31 | String processToCheck = "Payment Gateway"; 32 | int serviceOrderNumber = 319; 33 | 34 | try 35 | { 36 | System.out.println("\nService order processing . . . "); 37 | int serviceOrder = processServiceOrder(processToCheck, serviceOrderNumber); 38 | 39 | } 40 | catch(ArithmeticException ex) 41 | { 42 | System.out.println("\n\tPayment Gateway is offline. Your orders " + 43 | "\n\twill be automatically processed via batch "+ 44 | "\n\twhen the gateway is back online."); 45 | 46 | System.out.println("\n. . . continue processing service order."); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Chapter09/CH9IdempotencyExample/IdempotencyDriver.java: -------------------------------------------------------------------------------- 1 | package CH9IdempotencyExample; 2 | 3 | public class IdempotencyDriver { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("\n = = = = = = = = = = = = = = = = = = = = = = "); 8 | System.out.println("\t\tHOSPITAL INFORMATION SYSTEM"); 9 | System.out.println(" = = = = = = = = = = = = = = = = = = = = = = "); 10 | 11 | String tID = "XP330019"; 12 | 13 | // Admission 14 | Patient patient = new Patient(tID); 15 | System.out.println("\nPatient " + patient.getPatientID() + " admitted."); 16 | patient.setLengthOfStay(1); 17 | System.out.println("\tLength of stay : " + patient.getLengthOfStay()); 18 | 19 | // Lab Work 20 | System.out.println("\nPatient " + patient.getPatientID() + " received lab work."); 21 | patient.setLengthOfStay(1); 22 | System.out.println("\tLength of stay : " + patient.getLengthOfStay()); 23 | 24 | // Next Day 25 | patient.setDayCounted(false); 26 | System.out.println("\nPatient " + patient.getPatientID() + " received surgery."); 27 | patient.setLengthOfStay(1); 28 | System.out.println("\tLength of stay : " + patient.getLengthOfStay()); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Chapter09/CH9IdempotencyExample/Patient.java: -------------------------------------------------------------------------------- 1 | package CH9IdempotencyExample; 2 | 3 | public class Patient { 4 | 5 | String patientID; 6 | int lengthOfStay; 7 | boolean dayCounted; 8 | 9 | // constructor 10 | public Patient (String patientID) { 11 | this.patientID = patientID; 12 | this.lengthOfStay = 0; 13 | this.dayCounted = false; 14 | } 15 | 16 | // accessor methods 17 | public String getPatientID() { 18 | return this.patientID; 19 | } 20 | 21 | public int getLengthOfStay() { 22 | return this.lengthOfStay; 23 | } 24 | 25 | public boolean getDayCounted() { 26 | return this.dayCounted; 27 | } 28 | 29 | // mutator methods 30 | public void setPatientID(String patientID) { 31 | this.patientID = patientID; 32 | } 33 | 34 | public void setLengthOfStay(int lengthOfStay) { 35 | 36 | if (this.dayCounted) { 37 | System.out.println("\tIdempotency Implemented: Length of Stay already computed."); 38 | } else { 39 | this.lengthOfStay += lengthOfStay; 40 | this.dayCounted = true; 41 | } 42 | } 43 | 44 | public void setDayCounted(boolean counted) { 45 | this.dayCounted = counted; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/Corgi.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class Corgi implements CorgiState { 4 | 5 | // class variables 6 | private CorgiState corgiAwake; 7 | private CorgiState corgiEat; 8 | private CorgiState corgiPlay; 9 | private CorgiState corgiSleep; 10 | private CorgiState corgiSit; 11 | private CorgiState state; 12 | 13 | // constructor 14 | public Corgi(){ 15 | this.corgiAwake = new CorgiAwake(this); 16 | this.corgiEat = new CorgiEat(this); 17 | this.corgiPlay = new CorgiPlay(this); 18 | this.corgiSleep = new CorgiSleep(this); 19 | this.corgiSit = new CorgiSit(this); 20 | 21 | this.state = corgiAwake; 22 | } 23 | 24 | // overriding interface methods 25 | @Override 26 | public void awake() { 27 | state.awake(); 28 | setState(getCorgiSit()); 29 | } 30 | 31 | @Override 32 | public void walk() { 33 | state.walk(); 34 | setState(getCorgiSit()); 35 | } 36 | 37 | @Override 38 | public void eat() { 39 | state.eat(); 40 | setState(getCorgiSit()); 41 | } 42 | 43 | @Override 44 | public void play() { 45 | state.play(); 46 | setState(getCorgiSit()); 47 | } 48 | 49 | @Override 50 | public void sit() { 51 | state.sit(); 52 | setState(getCorgiSit()); 53 | } 54 | 55 | @Override 56 | public void sleep() { 57 | state.sleep(); 58 | } 59 | 60 | // accessor methods 61 | public CorgiState getCorgiAwake() { 62 | return corgiAwake; 63 | } 64 | 65 | public CorgiState getCorgiEat() { 66 | return corgiEat; 67 | } 68 | 69 | public CorgiState getCorgiPlay() { 70 | return corgiPlay; 71 | } 72 | 73 | public CorgiState getCorgiSleep() { 74 | return corgiSleep; 75 | } 76 | 77 | public CorgiState getState() { 78 | return state; 79 | } 80 | 81 | public CorgiState getCorgiSit() { 82 | return corgiSit; 83 | } 84 | 85 | // mutator methods 86 | public void setCorgiState(CorgiState state){ 87 | this.state = state; 88 | } 89 | 90 | public void setCorgiAwake(CorgiState corgiAwake) { 91 | this.corgiAwake = corgiAwake; 92 | } 93 | 94 | public void setCorgiEat(CorgiState corgiEat) { 95 | this.corgiEat = corgiEat; 96 | } 97 | 98 | public void setCorgiPlay(CorgiState corgiPlay) { 99 | this.corgiPlay = corgiPlay; 100 | } 101 | 102 | public void setCorgiSleep(CorgiState corgiSleep) { 103 | this.corgiSleep = corgiSleep; 104 | } 105 | 106 | public void setState(CorgiState state) { 107 | this.state = state; 108 | } 109 | 110 | public void setCorgiSit(CorgiState corgiSit) { 111 | this.corgiSit = corgiSit; 112 | } 113 | 114 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiAwake.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class CorgiAwake implements CorgiState{ 4 | 5 | private final Corgi corgi; 6 | 7 | public CorgiAwake(Corgi corgi){ 8 | this.corgi = corgi; 9 | } 10 | 11 | @Override 12 | public void awake() { 13 | System.out.println("The Corgi is AWAKE."); 14 | } 15 | @Override 16 | public void walk() { 17 | System.out.println("The Corgi is WALKING."); 18 | } 19 | 20 | @Override 21 | public void eat() { 22 | System.out.println("The Corgi is EATING."); 23 | corgi.setCorgiState(corgi.getCorgiEat()); 24 | } 25 | 26 | @Override 27 | public void play() { 28 | System.out.println("The Corgi is PLAYING."); 29 | corgi.setCorgiState(corgi.getCorgiPlay()); 30 | } 31 | 32 | @Override 33 | public void sit() { 34 | System.out.println("The Corgi is SITTING."); 35 | } 36 | 37 | @Override 38 | public void sleep() { 39 | corgi.setState(corgi.getCorgiSleep()); 40 | System.out.println("The Corgi is SLEEPING."); 41 | } 42 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiEat.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class CorgiEat implements CorgiState{ 4 | 5 | private final Corgi corgi; 6 | 7 | public CorgiEat(Corgi corgi){ 8 | this.corgi = corgi; 9 | } 10 | 11 | @Override 12 | public void awake() { 13 | System.out.println("The Corgi is AWAKE."); 14 | } 15 | 16 | @Override 17 | public void walk() { 18 | System.out.println("The Corgi is WALKING."); 19 | } 20 | 21 | @Override 22 | public void sit() { 23 | System.out.println("The Corgi is SITTING."); 24 | } 25 | 26 | @Override 27 | public void eat() { 28 | System.out.println("The Corgi is EATING"); 29 | corgi.setCorgiState(corgi.getCorgiSleep()); 30 | } 31 | 32 | @Override 33 | public void play() { 34 | System.out.println("The Corgi is PLAYING"); 35 | } 36 | 37 | @Override 38 | public void sleep() { 39 | System.out.println("The Corgi is SLEEPING."); 40 | } 41 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiPlay.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class CorgiPlay implements CorgiState { 4 | 5 | private final Corgi corgi; 6 | 7 | public CorgiPlay(Corgi corgi){ 8 | this.corgi = corgi; 9 | } 10 | 11 | @Override 12 | public void awake() { 13 | System.out.println("The Corgi is AWAKE."); 14 | } 15 | 16 | @Override 17 | public void walk() { 18 | System.out.println("The Corgi is WALKING."); 19 | } 20 | 21 | @Override 22 | public void sit() { 23 | System.out.println("The Corgi is SITTING."); 24 | } 25 | 26 | @Override 27 | public void eat() { 28 | System.out.println("The Corgi is EATING."); 29 | corgi.setCorgiState(corgi.getCorgiSleep()); 30 | } 31 | 32 | @Override 33 | public void play() { 34 | System.out.println("The Corgi is PLAYING."); 35 | } 36 | 37 | @Override 38 | public void sleep() { 39 | System.out.println("The Corgi is SLEEPING."); 40 | } 41 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiSit.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class CorgiSit implements CorgiState{ 4 | 5 | private final Corgi corgi; 6 | 7 | public CorgiSit(Corgi corgi){ 8 | this.corgi = corgi; 9 | } 10 | 11 | @Override 12 | public void awake() { 13 | System.out.println("\tThe Corgi is now AWAKE."); 14 | corgi.setState(corgi.getCorgiAwake()); 15 | } 16 | 17 | @Override 18 | public void walk() { 19 | System.out.println("The Corgi is SITTING and waiting for action..."); 20 | corgi.setState(corgi.getCorgiAwake()); 21 | System.out.println("\tThe Corgi is now WALKING"); 22 | } 23 | 24 | @Override 25 | public void eat() { 26 | System.out.println("The Corgi is SITTING and waiting for action..."); 27 | corgi.setCorgiState(corgi.getCorgiEat()); 28 | System.out.println("\tThe Corgi is now EATING."); 29 | } 30 | 31 | @Override 32 | public void play() { 33 | System.out.println("The Corgi is SITTING and waiting for action..."); 34 | corgi.setCorgiState(corgi.getCorgiPlay()); 35 | System.out.println("\tThe Corgi is now PLAYING."); 36 | } 37 | 38 | @Override 39 | public void sit() { 40 | System.out.println("The Corgi is SITTING and waiting for action..."); 41 | } 42 | 43 | @Override 44 | public void sleep() { 45 | System.out.println("Shhh; the Corgi is sleeping."); 46 | corgi.setState(corgi.getCorgiSleep()); 47 | System.out.println("\tThe Corgi is now SLEEPING."); 48 | } 49 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiSleep.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class CorgiSleep implements CorgiState{ 4 | 5 | private final Corgi corgi; 6 | 7 | public CorgiSleep(Corgi corgi){ 8 | this.corgi = corgi; 9 | } 10 | 11 | @Override 12 | public void awake() { 13 | System.out.println("The Corgi is AWAKE."); 14 | } 15 | 16 | @Override 17 | public void walk() { 18 | System.out.println("The Corgi cannot WALK when it is SLEEPING."); 19 | } 20 | 21 | @Override 22 | public void sit() { 23 | System.out.println("The Corgi is SITTING."); 24 | } 25 | 26 | @Override 27 | public void eat() { 28 | System.out.println("The Corgi cannot EAT when it is SLEEPING."); 29 | corgi.setCorgiState(corgi.getCorgiSleep()); 30 | } 31 | 32 | @Override 33 | public void play() { 34 | System.out.println("The Corgi cannot PLAY when it is SLEEPING."); 35 | } 36 | 37 | @Override 38 | public void sleep() { 39 | System.out.println("The Corgi is SLEEPING."); 40 | } 41 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiState.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public interface CorgiState { 4 | 5 | void awake(); 6 | void eat(); 7 | void play(); 8 | void sit(); 9 | void sleep(); 10 | void walk(); 11 | } 12 | -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/CorgiWalk.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class CorgiWalk implements CorgiState { 4 | 5 | private final Corgi corgi; 6 | 7 | public CorgiWalk(Corgi corgi){ 8 | this.corgi = corgi; 9 | } 10 | 11 | @Override 12 | public void awake() { 13 | System.out.println("The Corgi is AWAKE."); 14 | } 15 | 16 | @Override 17 | public void walk() { 18 | System.out.println("The Corgi is WALKING."); 19 | } 20 | 21 | @Override 22 | public void sit() { 23 | System.out.println("The Corgi is SITTING."); 24 | } 25 | 26 | @Override 27 | public void eat() { 28 | System.out.println("The Corgi is EATING."); 29 | corgi.setCorgiState(corgi.getCorgiSleep()); 30 | } 31 | 32 | @Override 33 | public void play() { 34 | System.out.println("The Corgi is PLAYING."); 35 | } 36 | 37 | @Override 38 | public void sleep() { 39 | System.out.println("The Corgi is SLEEPING."); 40 | } 41 | } -------------------------------------------------------------------------------- /Chapter09/CH9Stateless/StatelessDriver.java: -------------------------------------------------------------------------------- 1 | package CH9Stateless; 2 | 3 | public class StatelessDriver { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("\n = = = = = = = = = = = = = = ="); 8 | System.out.println("\tCORGI STATELESS SYSTEM"); 9 | System.out.println(" = = = = = = = = = = = = = = =\n"); 10 | 11 | Corgi corgi = new Corgi(); 12 | 13 | corgi.awake(); 14 | corgi.walk(); 15 | corgi.play(); 16 | corgi.eat(); 17 | corgi.walk(); 18 | corgi.sleep(); 19 | 20 | corgi.play(); 21 | corgi.sleep(); 22 | corgi.eat(); 23 | } 24 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Hands-On Design Patterns with Java 5 | 6 | Hands-On Design Patterns with Java 7 | 8 | This is the code repository for [Hands-On Design Patterns with Java](https://www.packtpub.com/application-development/hands-design-patterns-java?utm_source=github&utm_medium=repository&utm_campaign=9781789809770 ), published by Packt. 9 | 10 | **Learn design patterns that enable the building of large-scale software architectures** 11 | 12 | ## What is this book about? 13 | Java design patterns are reusable and proven solutions to software design problems. This book covers over 60 battle-tested design patterns used by developers to create functional, reusable, and flexible software. 14 | 15 | This book covers the following exciting features: 16 | Understand the significance of design patterns for software engineering 17 | Visualize software design with UML diagrams 18 | Strengthen your understanding of OOP to create reusable software systems 19 | Discover GOF design patterns to develop scalable applications 20 | Examine programming challenges and the design patterns that solve them 21 | Explore architectural patterns for microservices and cloud development 22 | 23 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1789809770) today! 24 | 25 | https://www.packtpub.com/ 27 | 28 | ## Instructions and Navigations 29 | All of the code is organized into folders. For example, Chapter04. 30 | 31 | The code will look like the following: 32 | ``` 33 | Mother() { 34 | System.out.println("Mother constructor executed."); 35 | } 36 | } 37 | ``` 38 | 39 | **Following is what you need for this book:** 40 | If you are a developer who wants to learn how to write clear, concise, and effective code for building production-ready applications, this book is for you. Familiarity with the fundamentals of Java is assumed. 41 | 42 | With the following software and hardware list you can run all code files present in the book (Chapter 1-9). 43 | ### Software and Hardware List 44 | | Chapter | Software required | OS required | 45 | | ------- | -------------------------------- | ---------------------------------- | 46 | | 1 | Modelio 3.x | Windows, Mac OS X, and Linux (Any) | 47 | | 2-9 | Java SE Development Kit (JDK) 12 | Windows, Mac OS X, and Linux (Any) | 48 | 49 | 50 | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://www.packtpub.com/sites/default/files/downloads/9781789809770_ColorImages.pdf). 51 | 52 | ### Related products 53 | * Java 11 Cookbook - Second Edition [[Packt]](https://www.packtpub.com/application-development/java-11-cookbook-second-edition?utm_source=github&utm_medium=repository&utm_campaign=9781789132359 ) [[Amazon]](https://www.amazon.com/dp/1789132355) 54 | 55 | * Mastering Java 11 - Second Edition [[Packt]](https://www.packtpub.com/application-development/mastering-java-11-second-edition?utm_source=github&utm_medium=repository&utm_campaign=9781789137613 ) [[Amazon]](https://www.amazon.com/dp/1789137616) 56 | 57 | 58 | 59 | ## Get to Know the Author 60 | **Dr Edward Lavieri** 61 | is a veteran software engineer and developer with a strong academic background. He earned a Doctorate of Computer Science from Colorado Technical University, an MS in Management Information Systems (Bowie State University), an MS in Education (Capella University), and an MS in Operations Management (University of Arkansas). He has been creating and teaching computer science courses since 2002. Edward retired from the U.S. Navy as a Command Master Chief after 25 years of active service. He is the founder and creative director of three19, a software design and development studio. Edward has authored more than a dozen technology books, including several on Java. 62 | 63 | 64 | 65 | ## Other books by the authors 66 | [LiveCode Mobile Development HOTSHOT](https://www.packtpub.com/application-development/livecode-mobile-development-hotshot?utm_source=github&utm_medium=repository&utm_campaign=9781849697484 ) 67 | 68 | [LiveCode Mobile Development Cookbook](https://www.packtpub.com/application-development/livecode-mobile-development-cookbook?utm_source=github&utm_medium=repository&utm_campaign=9781783558827 ) 69 | 70 | [Getting Started with Unity 5](https://www.packtpub.com/game-development/getting-started-unity-5?utm_source=github&utm_medium=repository&utm_campaign=9781784398316 ) 71 | 72 | [Mastering Java 9](https://www.packtpub.com/application-development/mastering-java-9?utm_source=github&utm_medium=repository&utm_campaign=9781786468734 ) 73 | 74 | [Learning AWS Lumberyard Game Development](https://www.packtpub.com/game-development/learning-aws-lumberyard-game-development?utm_source=github&utm_medium=repository&utm_campaign=9781786460868 ) 75 | 76 | ### Suggestions and Feedback 77 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSdy7dATC6QmEL81FIUuymZ0Wy9vH1jHkvpY57OiMeKGqib_Ow/viewform) if you have any feedback or suggestions. 78 | 79 | 80 | ### Download a free PDF 81 | 82 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
83 |

https://packt.link/free-ebook/9781789809770

--------------------------------------------------------------------------------