├── .gitignore ├── README.md ├── pom.xml └── src ├── main ├── java │ └── guru │ │ └── springframework │ │ └── gof │ │ ├── ChainofResponsibility │ │ ├── RequestorClient.java │ │ └── handlers │ │ │ ├── AbstractSupportHandler.java │ │ │ ├── BillingSupportHandler.java │ │ │ ├── GeneralSupportHandler.java │ │ │ └── TechnicalSupportHandler.java │ │ ├── GangOfFourApplication.java │ │ ├── abstractFactory │ │ ├── BasePizzaFactory.java │ │ ├── BaseToppingFactory.java │ │ ├── GourmetPizzaFactory.java │ │ ├── GourmetToppingFactory.java │ │ ├── SicilianPizzaFactory.java │ │ ├── SicilianToppingFactory.java │ │ ├── product │ │ │ ├── CheesePizza.java │ │ │ ├── PepperoniPizza.java │ │ │ ├── Pizza.java │ │ │ └── VeggiePizza.java │ │ └── topping │ │ │ ├── CaliforniaOilSauce.java │ │ │ ├── Cheese.java │ │ │ ├── GoatCheese.java │ │ │ ├── MozzarellaCheese.java │ │ │ ├── Sauce.java │ │ │ └── TomatoSauce.java │ │ ├── adapter │ │ ├── adaptee │ │ │ ├── CsvFormattable.java │ │ │ └── CsvFormatter.java │ │ ├── csvadapter │ │ │ └── CsvAdapterImpl.java │ │ └── source │ │ │ ├── NewLineFormatter.java │ │ │ └── TextFormattable.java │ │ ├── bridge │ │ ├── abstraction │ │ │ ├── EmailMessage.java │ │ │ ├── Message.java │ │ │ └── TextMessage.java │ │ └── implementation │ │ │ ├── EmailMessageSender.java │ │ │ ├── MessageSender.java │ │ │ └── TextMessageSender.java │ │ ├── builder │ │ ├── builders │ │ │ ├── ConcreteHouseBuilder.java │ │ │ ├── HouseBuilder.java │ │ │ └── PrefabricatedHouseBuilder.java │ │ ├── director │ │ │ └── ConstructionEngineer.java │ │ └── product │ │ │ └── House.java │ │ ├── command │ │ ├── commandobjects │ │ │ ├── CarMoveCommand.java │ │ │ ├── CarStopCommand.java │ │ │ ├── CommandBase.java │ │ │ ├── TopRotateCommand.java │ │ │ └── TopStopRotateCommand.java │ │ ├── invoker │ │ │ └── RemoteControl.java │ │ └── receiver │ │ │ ├── Car.java │ │ │ └── RotatingTop.java │ │ ├── composite │ │ ├── CatalogComponent.java │ │ ├── Product.java │ │ └── ProductCatalog.java │ │ ├── decorator │ │ ├── components │ │ │ ├── FlowerBouquet.java │ │ │ ├── OrchidBouquet.java │ │ │ └── RoseBouquet.java │ │ └── decorators │ │ │ ├── FlowerBouquetDecorator.java │ │ │ ├── Glitter.java │ │ │ ├── PaperWrapper.java │ │ │ └── RibbonBow.java │ │ ├── facade │ │ ├── controller │ │ │ └── OrderFulfillmentController.java │ │ ├── domain │ │ │ └── Product.java │ │ ├── servicefacade │ │ │ ├── OrderServiceFacade.java │ │ │ └── OrderServiceFacadeImpl.java │ │ └── subcomponents │ │ │ ├── InventoryService.java │ │ │ ├── PaymentService.java │ │ │ └── ShippingService.java │ │ ├── factoryMethod │ │ ├── BasePizzaFactory.java │ │ ├── CheesePizza.java │ │ ├── PepperoniPizza.java │ │ ├── Pizza.java │ │ ├── PizzaFactory.java │ │ └── VeggiePizza.java │ │ ├── flyweight │ │ ├── CarFactory.java │ │ ├── FlyweightMidgetCar.java │ │ ├── FlyweightSprintCar.java │ │ ├── RaceCar.java │ │ └── RaceCarClient.java │ │ ├── interpreter │ │ ├── AdditionExpression.java │ │ ├── Expression.java │ │ ├── ExpressionParser.java │ │ ├── MultiplicationExpression.java │ │ ├── NumberExpression.java │ │ ├── ParserUtil.java │ │ └── SubtractionExpression.java │ │ ├── iterator │ │ ├── DesignPattern.java │ │ ├── PatternAggregate.java │ │ ├── PatternAggregateImpl.java │ │ ├── PatternIterator.java │ │ └── PatternIteratorImpl.java │ │ ├── mediator │ │ ├── colleague │ │ │ ├── ArmedUnit.java │ │ │ ├── SoldierUnit.java │ │ │ └── TankUnit.java │ │ └── mediator │ │ │ ├── Commander.java │ │ │ └── CommanderImpl.java │ │ ├── memento │ │ ├── EmpCaretaker.java │ │ ├── EmpMemento.java │ │ └── EmpOriginator.java │ │ ├── observer │ │ ├── javaapi │ │ │ ├── Bidder.java │ │ │ └── Product.java │ │ └── observerimpl │ │ │ ├── Bidder.java │ │ │ ├── Observer.java │ │ │ ├── Product.java │ │ │ └── Subject.java │ │ ├── prototype │ │ ├── AuthorizedSignatory.java │ │ ├── DocumentPrototypeManager.java │ │ ├── NDAgreement.java │ │ ├── PrototypeCapableDocument.java │ │ └── TAndC.java │ │ ├── proxy │ │ ├── ReportGenerator.java │ │ ├── ReportGeneratorImpl.java │ │ ├── ReportGeneratorImplProxy.java │ │ └── Role.java │ │ ├── state │ │ ├── context │ │ │ └── CandyVendingMachine.java │ │ └── states │ │ │ ├── CandyVendingMachineState.java │ │ │ ├── ContainsCoinState.java │ │ │ ├── DispensedState.java │ │ │ ├── NoCandyState.java │ │ │ └── NoCoinState.java │ │ ├── strategy │ │ ├── context │ │ │ └── Encryptor.java │ │ └── strategies │ │ │ ├── AesEncryptionStrategy.java │ │ │ ├── BlowfishEncryptionStrategy.java │ │ │ └── EncryptionStrategy.java │ │ ├── templatemethod │ │ ├── InHouseAssortedPizzaMaker.java │ │ ├── NonVegPizzaMaker.java │ │ ├── PizzaMaker.java │ │ └── VegPizzaMaker.java │ │ └── visitor │ │ ├── structure │ │ ├── MailClient.java │ │ ├── OperaMailClient.java │ │ ├── SquirrelMailClient.java │ │ └── ZimbraMailClient.java │ │ └── visitors │ │ ├── LinuxMailClientVisitor.java │ │ ├── MacMailClientVisitor.java │ │ ├── MailClientVisitor.java │ │ └── WindowsMailClientVisitor.java └── resources │ └── application.properties └── test └── java └── guru └── springframework └── gof ├── ChainofResponsibility └── RequestorClientTest.java ├── GangOfFourApplicationTests.java ├── abstractFactory ├── GourmetPizzaFactoryTest.java └── SicilianPizzaFactoryTest.java ├── adapter └── source │ └── NewLineFormatterTest.java ├── bridge └── abstraction │ └── MessageTest.java ├── builder └── director │ └── ConstructionEngineerTest.java ├── command └── invoker │ └── RemoteControlTest.java ├── composite └── CatalogComponentTest.java ├── decorator └── components │ └── FlowerBouquetTest.java ├── facade └── controller │ └── OrderFulfillmentControllerTest.java ├── factoryMethod └── PizzaFactoryTest.java ├── flyweight └── RaceCarClientTest.java ├── interpreter └── ExpressionParserTest.java ├── iterator └── PatternAggregateImplTest.java ├── mediator └── mediator │ └── CommanderImplTest.java ├── memento └── EmpOriginatorTest.java ├── observer ├── javaapi │ └── ObservableJavaAPITest.java └── observerimpl │ └── ObserverTest.java ├── prototype └── DocumentPrototypeManagerTest.java ├── proxy └── ReportGeneratorImplProxyTest.java ├── state └── context │ └── CandyVendingMachineTest.java ├── strategy └── context │ └── EncryptorTest.java ├── templatemethod └── PizzaMakerTest.java └── visitor └── visitors └── MailClientVisitorTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.rar 19 | *.tar 20 | *.zip 21 | 22 | # Logs and databases # 23 | ###################### 24 | *.log 25 | *.sqlite 26 | 27 | # OS generated files # 28 | ###################### 29 | .DS_Store 30 | .DS_Store? 31 | ._* 32 | .Spotlight-V100 33 | .Trashes 34 | ehthumbs.db 35 | Thumbs.db 36 | 37 | .project 38 | .classpath 39 | .idea 40 | *.iml 41 | atlassian-ide-plugin.xml 42 | target 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gang of Four Design Patterns 2 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | guru.springframework 7 | gof 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | Gang of Four 12 | GoF Design Patterns 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.2.3.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | guru.springframework.gof.GangOfFourApplication 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-maven-plugin 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/ChainofResponsibility/RequestorClient.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.ChainofResponsibility; 2 | 3 | import guru.springframework.gof.ChainofResponsibility.handlers.BillingSupportHandler; 4 | import guru.springframework.gof.ChainofResponsibility.handlers.AbstractSupportHandler; 5 | import guru.springframework.gof.ChainofResponsibility.handlers.GeneralSupportHandler; 6 | import guru.springframework.gof.ChainofResponsibility.handlers.TechnicalSupportHandler; 7 | 8 | public class RequestorClient { 9 | 10 | public static AbstractSupportHandler getHandlerChain(){ 11 | 12 | 13 | AbstractSupportHandler technicalSupportHandler = new TechnicalSupportHandler( AbstractSupportHandler.TECHNICAL); 14 | AbstractSupportHandler billingSupportHandler = new BillingSupportHandler( AbstractSupportHandler.BILLING); 15 | AbstractSupportHandler generalSupportHandler = new GeneralSupportHandler(AbstractSupportHandler.GENERAL); 16 | 17 | technicalSupportHandler.setNextHandler(billingSupportHandler); 18 | billingSupportHandler.setNextHandler(generalSupportHandler); 19 | 20 | return technicalSupportHandler; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/ChainofResponsibility/handlers/AbstractSupportHandler.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.ChainofResponsibility.handlers; 2 | 3 | public abstract class AbstractSupportHandler { 4 | 5 | public static int TECHNICAL = 10; 6 | public static int BILLING = 20; 7 | public static int GENERAL = 30; 8 | 9 | protected int level; 10 | 11 | protected AbstractSupportHandler nextHandler; 12 | public void setNextHandler(AbstractSupportHandler nextHandler){ 13 | this.nextHandler=nextHandler; 14 | } 15 | 16 | public void receiveRequest(int level, String message){ 17 | if(this.level <= level){ 18 | handleRequest(message); 19 | } 20 | if(nextHandler !=null){ 21 | nextHandler.receiveRequest(level, message); 22 | } 23 | } 24 | 25 | abstract protected void handleRequest(String message); 26 | 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/ChainofResponsibility/handlers/BillingSupportHandler.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.ChainofResponsibility.handlers; 2 | 3 | public class BillingSupportHandler extends AbstractSupportHandler { 4 | 5 | public BillingSupportHandler(int level){ 6 | this.level = level; 7 | } 8 | 9 | @Override 10 | protected void handleRequest (String message){ 11 | System.out.println("BillingSupportHandler: Processing request. " + message); 12 | } 13 | 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/ChainofResponsibility/handlers/GeneralSupportHandler.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.ChainofResponsibility.handlers; 2 | 3 | 4 | public class GeneralSupportHandler extends AbstractSupportHandler { 5 | 6 | public GeneralSupportHandler(int level){ 7 | this.level = level; 8 | } 9 | 10 | @Override 11 | protected void handleRequest(String message) { 12 | System.out.println("GeneralSupportHandler: Processing request. " + message); 13 | 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/ChainofResponsibility/handlers/TechnicalSupportHandler.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.ChainofResponsibility.handlers; 2 | 3 | 4 | public class TechnicalSupportHandler extends AbstractSupportHandler { 5 | 6 | public TechnicalSupportHandler(int level){ 7 | this.level = level; 8 | } 9 | 10 | @Override 11 | protected void handleRequest(String message) { 12 | System.out.println("TechnicalSupportHandler: Processing request " + message); 13 | 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/GangOfFourApplication.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class GangOfFourApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(GangOfFourApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/BasePizzaFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | 4 | import guru.springframework.gof.abstractFactory.product.Pizza; 5 | 6 | public abstract class BasePizzaFactory { 7 | 8 | public abstract Pizza createPizza(String type); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/BaseToppingFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | import guru.springframework.gof.abstractFactory.topping.Cheese; 4 | import guru.springframework.gof.abstractFactory.topping.Sauce; 5 | 6 | public abstract class BaseToppingFactory { 7 | public abstract Cheese createCheese(); 8 | public abstract Sauce createSauce(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/GourmetPizzaFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | 4 | import guru.springframework.gof.abstractFactory.product.CheesePizza; 5 | import guru.springframework.gof.abstractFactory.product.PepperoniPizza; 6 | import guru.springframework.gof.abstractFactory.product.Pizza; 7 | import guru.springframework.gof.abstractFactory.product.VeggiePizza; 8 | 9 | public class GourmetPizzaFactory extends BasePizzaFactory { 10 | 11 | @Override 12 | public Pizza createPizza(String type){ 13 | Pizza pizza; 14 | BaseToppingFactory toppingFactory= new GourmetToppingFactory(); 15 | switch (type.toLowerCase()) 16 | { 17 | case "cheese": 18 | pizza = new CheesePizza(toppingFactory); 19 | break; 20 | case "pepperoni": 21 | pizza = new PepperoniPizza(toppingFactory); 22 | break; 23 | case "veggie": 24 | pizza = new VeggiePizza(toppingFactory); 25 | break; 26 | default: throw new IllegalArgumentException("No such pizza."); 27 | } 28 | 29 | pizza.addIngredients(); 30 | pizza.bakePizza(); 31 | return pizza; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/GourmetToppingFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | import guru.springframework.gof.abstractFactory.topping.CaliforniaOilSauce; 4 | import guru.springframework.gof.abstractFactory.topping.Cheese; 5 | import guru.springframework.gof.abstractFactory.topping.GoatCheese; 6 | import guru.springframework.gof.abstractFactory.topping.Sauce; 7 | 8 | public class GourmetToppingFactory extends BaseToppingFactory{ 9 | @Override 10 | public Cheese createCheese(){return new GoatCheese();} 11 | @Override 12 | public Sauce createSauce(){return new CaliforniaOilSauce();} 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/SicilianPizzaFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | 4 | import guru.springframework.gof.abstractFactory.product.CheesePizza; 5 | import guru.springframework.gof.abstractFactory.product.PepperoniPizza; 6 | import guru.springframework.gof.abstractFactory.product.Pizza; 7 | import guru.springframework.gof.abstractFactory.product.VeggiePizza; 8 | 9 | public class SicilianPizzaFactory extends BasePizzaFactory { 10 | 11 | @Override 12 | public Pizza createPizza(String type){ 13 | Pizza pizza; 14 | BaseToppingFactory toppingFactory= new SicilianToppingFactory(); 15 | switch (type.toLowerCase()) 16 | { 17 | case "cheese": 18 | pizza = new CheesePizza(toppingFactory); 19 | break; 20 | case "pepperoni": 21 | pizza = new PepperoniPizza(toppingFactory); 22 | break; 23 | case "veggie": 24 | pizza = new VeggiePizza(toppingFactory); 25 | break; 26 | default: throw new IllegalArgumentException("No such pizza."); 27 | } 28 | 29 | pizza.addIngredients(); 30 | pizza.bakePizza(); 31 | return pizza; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/SicilianToppingFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | import guru.springframework.gof.abstractFactory.topping.Cheese; 4 | import guru.springframework.gof.abstractFactory.topping.MozzarellaCheese; 5 | import guru.springframework.gof.abstractFactory.topping.Sauce; 6 | import guru.springframework.gof.abstractFactory.topping.TomatoSauce; 7 | 8 | public class SicilianToppingFactory extends BaseToppingFactory{ 9 | @Override 10 | public Cheese createCheese(){return new MozzarellaCheese();} 11 | @Override 12 | public Sauce createSauce(){return new TomatoSauce();} 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/product/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.product; 2 | 3 | import guru.springframework.gof.abstractFactory.BaseToppingFactory; 4 | 5 | public class CheesePizza extends Pizza { 6 | BaseToppingFactory toppingFactory; 7 | public CheesePizza(BaseToppingFactory toppingFactory){ 8 | 9 | this.toppingFactory=toppingFactory; 10 | } 11 | @Override 12 | public void addIngredients() { 13 | System.out.println("Preparing ingredients for cheese pizza."); 14 | toppingFactory.createCheese(); 15 | toppingFactory.createSauce(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/product/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.product; 2 | 3 | import guru.springframework.gof.abstractFactory.BaseToppingFactory; 4 | public class PepperoniPizza extends Pizza { 5 | BaseToppingFactory toppingFactory; 6 | public PepperoniPizza(BaseToppingFactory toppingFactory) 7 | { 8 | this.toppingFactory=toppingFactory; 9 | } 10 | @Override 11 | public void addIngredients() { 12 | System.out.println("Preparing ingredients for pepperoni pizza."); 13 | toppingFactory.createCheese(); 14 | toppingFactory.createSauce(); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/product/Pizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.product; 2 | 3 | public abstract class Pizza { 4 | public abstract void addIngredients(); 5 | public void bakePizza() { 6 | System.out.println("Pizza baked at 400 for 20 minutes."); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/product/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.product; 2 | 3 | import guru.springframework.gof.abstractFactory.BaseToppingFactory; 4 | 5 | public class VeggiePizza extends Pizza { 6 | BaseToppingFactory toppingFactory; 7 | public VeggiePizza(BaseToppingFactory toppingFactory) 8 | { 9 | this.toppingFactory=toppingFactory; 10 | } 11 | @Override 12 | public void addIngredients() { 13 | 14 | System.out.println("Preparing ingredients for veggie pizza."); 15 | toppingFactory.createCheese(); 16 | toppingFactory.createSauce(); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/topping/CaliforniaOilSauce.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.topping; 2 | 3 | public class CaliforniaOilSauce implements Sauce { 4 | public CaliforniaOilSauce(){ 5 | prepareSauce(); 6 | } 7 | @Override 8 | public void prepareSauce() { 9 | System.out.println("Preparing california oil sauce.."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/topping/Cheese.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.topping; 2 | 3 | public interface Cheese { 4 | void prepareCheese(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/topping/GoatCheese.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.topping; 2 | 3 | public class GoatCheese implements Cheese { 4 | 5 | public GoatCheese(){ 6 | prepareCheese(); 7 | } 8 | @Override 9 | public void prepareCheese(){ 10 | System.out.println("Preparing goat cheese..."); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/topping/MozzarellaCheese.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.topping; 2 | 3 | public class MozzarellaCheese implements Cheese{ 4 | public MozzarellaCheese(){prepareCheese(); 5 | } 6 | 7 | @Override 8 | public void prepareCheese() { 9 | System.out.println("Preparing mozzarella cheese..."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/topping/Sauce.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.topping; 2 | 3 | public interface Sauce { 4 | void prepareSauce(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/abstractFactory/topping/TomatoSauce.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory.topping; 2 | 3 | public class TomatoSauce implements Sauce { 4 | public TomatoSauce(){ 5 | prepareSauce(); 6 | } 7 | @Override 8 | public void prepareSauce() { 9 | System.out.println("Preparing tomato sauce.."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/adapter/adaptee/CsvFormattable.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.adapter.adaptee; 2 | 3 | 4 | public interface CsvFormattable { 5 | String formatCsvText(String text); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/adapter/adaptee/CsvFormatter.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.adapter.adaptee; 2 | 3 | 4 | public class CsvFormatter implements CsvFormattable{ 5 | @Override 6 | public String formatCsvText(String text){ 7 | String formattedText=text.replace(".",","); 8 | return formattedText; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/adapter/csvadapter/CsvAdapterImpl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.adapter.csvadapter; 2 | 3 | import guru.springframework.gof.adapter.adaptee.CsvFormattable; 4 | import guru.springframework.gof.adapter.source.TextFormattable; 5 | 6 | public class CsvAdapterImpl implements TextFormattable { 7 | CsvFormattable csvFormatter; 8 | public CsvAdapterImpl(CsvFormattable csvFormatter){ 9 | this.csvFormatter=csvFormatter; 10 | } 11 | @Override 12 | public String formatText(String text) 13 | { 14 | String formattedText=csvFormatter.formatCsvText(text); 15 | return formattedText; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/adapter/source/NewLineFormatter.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.adapter.source; 2 | 3 | 4 | public class NewLineFormatter implements TextFormattable{ 5 | @Override 6 | public String formatText(String text) 7 | { 8 | String formattedText=text.replace(".","\n"); 9 | return formattedText; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/adapter/source/TextFormattable.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.adapter.source; 2 | 3 | public interface TextFormattable { 4 | 5 | String formatText(String text); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/bridge/abstraction/EmailMessage.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.abstraction; 2 | import guru.springframework.gof.bridge.implementation.MessageSender; 3 | 4 | public class EmailMessage extends Message{ 5 | public EmailMessage(MessageSender messageSender){ 6 | super(messageSender); 7 | } 8 | @Override 9 | public void send(){ 10 | messageSender.sendMessage(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/bridge/abstraction/Message.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.abstraction; 2 | 3 | import guru.springframework.gof.bridge.implementation.MessageSender; 4 | 5 | public abstract class Message { 6 | MessageSender messageSender; 7 | public Message(MessageSender messageSender){ 8 | this.messageSender=messageSender; 9 | } 10 | abstract public void send(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/bridge/abstraction/TextMessage.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.abstraction; 2 | 3 | import guru.springframework.gof.bridge.implementation.MessageSender; 4 | 5 | public class TextMessage extends Message{ 6 | 7 | public TextMessage(MessageSender messageSender){ 8 | super(messageSender); 9 | } 10 | @Override 11 | public void send(){ 12 | messageSender.sendMessage(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/bridge/implementation/EmailMessageSender.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.implementation; 2 | 3 | 4 | public class EmailMessageSender implements MessageSender{ 5 | @Override 6 | public void sendMessage(){ 7 | System.out.println("EmailMessageSender: Sending email message..."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/bridge/implementation/MessageSender.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.implementation; 2 | 3 | public interface MessageSender { 4 | public void sendMessage(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/bridge/implementation/TextMessageSender.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.implementation; 2 | 3 | 4 | public class TextMessageSender implements MessageSender { 5 | @Override 6 | public void sendMessage(){ 7 | System.out.println("TextMessageSender: Sending text message..."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/builder/builders/ConcreteHouseBuilder.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.builder.builders; 2 | 3 | import guru.springframework.gof.builder.product.House; 4 | 5 | public class ConcreteHouseBuilder implements HouseBuilder{ 6 | private House house; 7 | 8 | public ConcreteHouseBuilder() { 9 | this.house = new House(); 10 | } 11 | @Override 12 | public void buildFoundation() { 13 | house.setFoundation("Concrete, brick, and stone"); 14 | System.out.println("ConcreteHouseBuilder: Foundation complete..."); 15 | } 16 | @Override 17 | public void buildStructure(){ 18 | house.setStructure("Concrete, mortar, brick, and reinforced steel"); 19 | System.out.println("ConcreteHouseBuilder: Structure complete..."); 20 | } 21 | @Override 22 | public void buildRoof(){ 23 | house.setRoof("Concrete and reinforced steel"); 24 | System.out.println("ConcreteHouseBuilder: Roof complete..."); 25 | } 26 | @Override 27 | public void paintHouse(){ 28 | house.setPainted(true); 29 | System.out.println("ConcreteHouseBuilder: Painting complete..."); 30 | } 31 | @Override 32 | public void furnishHouse(){ 33 | house.setFurnished(true); 34 | System.out.println("ConcreteHouseBuilder: Furnishing complete..."); 35 | } 36 | public House getHouse() { 37 | System.out.println("ConcreteHouseBuilder: Concrete house complete..."); 38 | return this.house; 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/builder/builders/HouseBuilder.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.builder.builders; 2 | 3 | import guru.springframework.gof.builder.product.House; 4 | 5 | public interface HouseBuilder { 6 | void buildFoundation(); 7 | void buildStructure(); 8 | void buildRoof(); 9 | void paintHouse(); 10 | void furnishHouse(); 11 | House getHouse(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/builder/builders/PrefabricatedHouseBuilder.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.builder.builders; 2 | 3 | import guru.springframework.gof.builder.product.House; 4 | 5 | public class PrefabricatedHouseBuilder implements HouseBuilder{ 6 | private House house; 7 | 8 | public PrefabricatedHouseBuilder() { 9 | this.house = new House(); 10 | } 11 | @Override 12 | public void buildFoundation() { 13 | house.setFoundation("Wood, laminate, and PVC flooring"); 14 | System.out.println("PrefabricatedHouseBuilder: Foundation complete..."); 15 | } 16 | @Override 17 | public void buildStructure(){ 18 | house.setStructure("Structural steels and wooden wall panels"); 19 | System.out.println("PrefabricatedHouseBuilder: Structure complete..."); 20 | } 21 | @Override 22 | public void buildRoof(){ 23 | house.setRoof("Roofing sheets"); 24 | System.out.println("PrefabricatedHouseBuilder: Roof complete..."); 25 | } 26 | @Override 27 | public void paintHouse(){ 28 | house.setPainted(false); 29 | System.out.println("PrefabricatedHouseBuilder: Painting not required..."); 30 | } 31 | @Override 32 | public void furnishHouse(){ 33 | house.setFurnished(true); 34 | System.out.println("PrefabricatedHouseBuilder: Furnishing complete..."); 35 | } 36 | public House getHouse() { 37 | System.out.println("PrefabricatedHouseBuilder: Prefabricated house complete..."); 38 | return this.house; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/builder/director/ConstructionEngineer.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.builder.director; 2 | 3 | import guru.springframework.gof.builder.builders.HouseBuilder; 4 | import guru.springframework.gof.builder.product.House; 5 | 6 | public class ConstructionEngineer { 7 | private HouseBuilder houseBuilder; 8 | public ConstructionEngineer(HouseBuilder houseBuilder){ 9 | this.houseBuilder = houseBuilder; 10 | } 11 | 12 | public House constructHouse() { 13 | this.houseBuilder.buildFoundation(); 14 | this.houseBuilder.buildStructure(); 15 | this.houseBuilder.buildRoof(); 16 | this.houseBuilder.paintHouse(); 17 | this.houseBuilder.furnishHouse(); 18 | return this.houseBuilder.getHouse(); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/builder/product/House.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.builder.product; 2 | 3 | public class House { 4 | private String foundation; 5 | private String structure; 6 | private String roof; 7 | private boolean furnished; 8 | private boolean painted; 9 | 10 | public void setFoundation(String foundation) { 11 | this. foundation = foundation; 12 | } 13 | public void setStructure(String structure) { 14 | this.structure = structure; 15 | } 16 | public void setRoof(String roof) { 17 | this.roof = roof; 18 | } 19 | public void setFurnished(boolean furnished) { 20 | this.furnished = furnished; 21 | } 22 | public void setPainted(boolean painted) { 23 | this.painted = painted; 24 | } 25 | @Override 26 | public String toString() { 27 | return "Foundation - " + foundation + " Structure - " + structure + " Roof - " + roof +" Is Furnished? "+furnished+" Is Painted? "+painted; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/commandobjects/CarMoveCommand.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.commandobjects; 2 | 3 | import guru.springframework.gof.command.receiver.Car; 4 | 5 | public class CarMoveCommand implements CommandBase { 6 | private Car car; 7 | public CarMoveCommand(Car car){ 8 | this.car=car; 9 | } 10 | @Override 11 | public void execute(){ 12 | System.out.println("CarMoveCommand.execute(): Invoking move() on Car"); 13 | car.move(); 14 | } 15 | @Override 16 | public void undo(){ 17 | System.out.println("CarMoveCommand.undo(): Undoing previous action->Invoking stop() on Car"); 18 | car.stop(); 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/commandobjects/CarStopCommand.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.commandobjects; 2 | 3 | 4 | import guru.springframework.gof.command.receiver.Car; 5 | 6 | public class CarStopCommand implements CommandBase{ 7 | private Car car; 8 | public CarStopCommand(Car car){ 9 | this.car=car; 10 | } 11 | @Override 12 | public void execute(){ 13 | System.out.println("CarStopCommand.execute(): Invoking stop() on Car"); 14 | car.stop(); 15 | } 16 | @Override 17 | public void undo() 18 | { 19 | System.out.println("CarStopCommand.undo(): Undoing previous action-> Invoking move() on Car"); 20 | car.move(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/commandobjects/CommandBase.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.commandobjects; 2 | 3 | 4 | public interface CommandBase { 5 | void execute(); 6 | void undo(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/commandobjects/TopRotateCommand.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.commandobjects; 2 | 3 | 4 | import guru.springframework.gof.command.receiver.RotatingTop; 5 | 6 | public class TopRotateCommand implements CommandBase{ 7 | RotatingTop rotatingTop; 8 | public TopRotateCommand(RotatingTop rotatingTop){ 9 | this.rotatingTop=rotatingTop; 10 | } 11 | @Override 12 | public void execute(){ 13 | System.out.println("TopRotateCommand.execute(): Invoking startRotating() on RotatingTop"); 14 | rotatingTop.startRotating(); 15 | } 16 | @Override 17 | public void undo(){ 18 | System.out.println("TopRotateCommand.undo(): Undoing previous action->Invoking stopRotating() on RotatingTop"); 19 | rotatingTop.stopRotating(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/commandobjects/TopStopRotateCommand.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.commandobjects; 2 | 3 | 4 | import guru.springframework.gof.command.receiver.RotatingTop; 5 | 6 | public class TopStopRotateCommand implements CommandBase{ 7 | RotatingTop rotatingTop; 8 | public TopStopRotateCommand(RotatingTop rotatingTop){ 9 | this.rotatingTop=rotatingTop; 10 | } 11 | @Override 12 | public void execute(){ 13 | System.out.println("TopStopRotateCommand.execute(): Invoking stopRotating() on RotatingTop"); 14 | rotatingTop.stopRotating(); 15 | } 16 | @Override 17 | public void undo(){ 18 | System.out.println("TopStopRotateCommand.undo(): Undoing previous action->Invoking startRotating() on RotatingTop"); 19 | rotatingTop.startRotating(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/invoker/RemoteControl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.invoker; 2 | 3 | 4 | import guru.springframework.gof.command.commandobjects.CommandBase; 5 | 6 | public class RemoteControl { 7 | CommandBase onCommand, offCommand, undoCommand; 8 | 9 | public void onButtonPressed(CommandBase onCommand){ 10 | this.onCommand=onCommand; 11 | onCommand.execute(); 12 | undoCommand=onCommand; 13 | } 14 | 15 | public void offButtonPressed(CommandBase offCommand){ 16 | this.offCommand=offCommand; 17 | offCommand.execute(); 18 | undoCommand=offCommand; 19 | } 20 | public void undoButtonPressed(){ 21 | undoCommand.undo(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/receiver/Car.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.receiver; 2 | 3 | 4 | public class Car { 5 | public void move() 6 | { 7 | System.out.println("Car is moving"); 8 | } 9 | public void stop() 10 | { 11 | System.out.println("Car has stopped"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/command/receiver/RotatingTop.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.receiver; 2 | 3 | 4 | public class RotatingTop { 5 | public void startRotating(){ 6 | System.out.println("Top has start rotating"); 7 | } 8 | public void stopRotating(){ 9 | System.out.println("Top has stopped rotating"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/composite/CatalogComponent.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.composite; 2 | 3 | 4 | public abstract class CatalogComponent { 5 | 6 | public void add(CatalogComponent catalogComponent){ 7 | throw new UnsupportedOperationException("Cannot add item to catalog."); 8 | } 9 | 10 | public void remove(CatalogComponent catalogComponent){ 11 | throw new UnsupportedOperationException("Cannot remove item from catalog."); 12 | } 13 | 14 | public String getName(){ 15 | throw new UnsupportedOperationException("Cannot return name."); 16 | } 17 | 18 | public double getPrice(){ 19 | throw new UnsupportedOperationException("Cannot return price."); 20 | } 21 | 22 | 23 | public void print(){ 24 | throw new UnsupportedOperationException("Cannot print."); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/composite/Product.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.composite; 2 | 3 | 4 | public class Product extends CatalogComponent{ 5 | 6 | private String name; 7 | private double price; 8 | public Product (String name, double price){ 9 | this.name=name; 10 | this.price=price; 11 | } 12 | 13 | @Override 14 | public String getName() { 15 | return this.name; 16 | } 17 | 18 | 19 | @Override 20 | public double getPrice() { 21 | return this.price; 22 | } 23 | 24 | @Override 25 | public void print(){ 26 | System.out.println("Product name: "+name+" Price: "+price); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/composite/ProductCatalog.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.composite; 2 | 3 | 4 | import java.util.ArrayList; 5 | 6 | public class ProductCatalog extends CatalogComponent{ 7 | private ArrayList items=new ArrayList<>(); 8 | private String name; 9 | public ProductCatalog(String name){ 10 | this.name=name; 11 | } 12 | @Override 13 | public String getName() { 14 | return name; 15 | } 16 | @Override 17 | public void print(){ 18 | 19 | for(CatalogComponent comp : items) 20 | { 21 | comp.print(); 22 | } 23 | } 24 | 25 | @Override 26 | public void add(CatalogComponent catalogComponent){ 27 | items.add(catalogComponent); 28 | } 29 | 30 | @Override 31 | public void remove(CatalogComponent catalogComponent){ 32 | items.remove(catalogComponent); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/components/FlowerBouquet.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.components; 2 | 3 | public abstract class FlowerBouquet { 4 | String description; 5 | public String getDescription() { 6 | return description; 7 | } 8 | public abstract double cost(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/components/OrchidBouquet.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.components; 2 | 3 | 4 | public class OrchidBouquet extends FlowerBouquet{ 5 | public OrchidBouquet(){ 6 | description = "Orchid bouquet"; 7 | } 8 | public double cost(){ 9 | return 29.0; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/components/RoseBouquet.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.components; 2 | 3 | public class RoseBouquet extends FlowerBouquet{ 4 | 5 | public RoseBouquet(){ 6 | description = "Rose bouquet"; 7 | } 8 | public double cost(){ 9 | return 12.0; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/decorators/FlowerBouquetDecorator.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.decorators; 2 | 3 | 4 | import guru.springframework.gof.decorator.components.FlowerBouquet; 5 | 6 | public abstract class FlowerBouquetDecorator extends FlowerBouquet { 7 | public abstract String getDescription(); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/decorators/Glitter.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.decorators; 2 | 3 | import guru.springframework.gof.decorator.components.FlowerBouquet; 4 | 5 | public class Glitter extends FlowerBouquetDecorator{ 6 | FlowerBouquet flowerBouquet; 7 | public Glitter(FlowerBouquet flowerBouquet){ 8 | this.flowerBouquet=flowerBouquet; 9 | } 10 | public String getDescription(){ 11 | return flowerBouquet.getDescription()+", glitter"; 12 | } 13 | public double cost() 14 | { 15 | return 4+flowerBouquet.cost(); 16 | } 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/decorators/PaperWrapper.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.decorators; 2 | 3 | 4 | import guru.springframework.gof.decorator.components.FlowerBouquet; 5 | 6 | public class PaperWrapper extends FlowerBouquetDecorator{ 7 | 8 | FlowerBouquet flowerBouquet; 9 | public PaperWrapper(FlowerBouquet flowerBouquet){ 10 | this.flowerBouquet=flowerBouquet; 11 | } 12 | public String getDescription(){ 13 | return flowerBouquet.getDescription()+", paper wrap"; 14 | } 15 | public double cost() 16 | { 17 | return 3+flowerBouquet.cost(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/decorator/decorators/RibbonBow.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.decorators; 2 | 3 | import guru.springframework.gof.decorator.components.FlowerBouquet; 4 | 5 | public class RibbonBow extends FlowerBouquetDecorator{ 6 | FlowerBouquet flowerBouquet; 7 | public RibbonBow(FlowerBouquet flowerBouquet){ 8 | this.flowerBouquet=flowerBouquet; 9 | } 10 | public String getDescription(){ 11 | return flowerBouquet.getDescription()+", ribbon bow"; 12 | } 13 | public double cost() 14 | { 15 | return 6.5+flowerBouquet.cost(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/controller/OrderFulfillmentController.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.controller; 2 | 3 | import guru.springframework.gof.facade.servicefacade.OrderServiceFacade; 4 | 5 | public class OrderFulfillmentController { 6 | OrderServiceFacade facade; 7 | boolean orderFulfilled=false; 8 | public void orderProduct(int productId) { 9 | orderFulfilled=facade.placeOrder(productId); 10 | System.out.println("OrderFulfillmentController: Order fulfillment completed. "); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/domain/Product.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.domain; 2 | public class Product { 3 | public int productId; 4 | public String name; 5 | public Product(){} 6 | public Product(int productId, String name){ 7 | this.productId=productId; 8 | this.name=name; 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/servicefacade/OrderServiceFacade.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.servicefacade; 2 | 3 | 4 | public interface OrderServiceFacade { 5 | boolean placeOrder(int productId); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/servicefacade/OrderServiceFacadeImpl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.servicefacade; 2 | 3 | import guru.springframework.gof.facade.domain.Product; 4 | import guru.springframework.gof.facade.subcomponents.PaymentService; 5 | import guru.springframework.gof.facade.subcomponents.ShippingService; 6 | import guru.springframework.gof.facade.subcomponents.InventoryService; 7 | 8 | public class OrderServiceFacadeImpl implements OrderServiceFacade{ 9 | 10 | public boolean placeOrder(int pId){ 11 | boolean orderFulfilled=false; 12 | Product product=new Product(); 13 | product.productId=pId; 14 | if(InventoryService.isAvailable(product)) 15 | { 16 | System.out.println("Product with ID: "+ product.productId+" is available."); 17 | boolean paymentConfirmed= PaymentService.makePayment(); 18 | if(paymentConfirmed){ 19 | System.out.println("Payment confirmed..."); 20 | ShippingService.shipProduct(product); 21 | System.out.println("Product shipped..."); 22 | orderFulfilled=true; 23 | } 24 | } 25 | return orderFulfilled; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/subcomponents/InventoryService.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.subcomponents; 2 | 3 | 4 | import guru.springframework.gof.facade.domain.Product; 5 | 6 | public class InventoryService { 7 | public static boolean isAvailable(Product product){ 8 | /*Check Warehouse database for product availability*/ 9 | return true; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/subcomponents/PaymentService.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.subcomponents; 2 | 3 | public class PaymentService { 4 | public static boolean makePayment(){ 5 | /*Connect with payment gateway for payment*/ 6 | return true; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/facade/subcomponents/ShippingService.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.subcomponents; 2 | 3 | import guru.springframework.gof.facade.domain.Product; 4 | 5 | public class ShippingService { 6 | public static void shipProduct(Product product){ 7 | /*Connect with external shipment service to ship product*/ 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/factoryMethod/BasePizzaFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | public abstract class BasePizzaFactory { 4 | 5 | public abstract Pizza createPizza(String type); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/factoryMethod/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | public class CheesePizza extends Pizza { 4 | 5 | @Override 6 | public void addIngredients() { 7 | System.out.println("Preparing ingredients for cheese pizza."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/factoryMethod/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | public class PepperoniPizza extends Pizza { 4 | @Override 5 | public void addIngredients() { 6 | System.out.println("Preparing ingredients for pepperoni pizza."); 7 | } 8 | } -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/factoryMethod/Pizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | public abstract class Pizza { 4 | public abstract void addIngredients(); 5 | 6 | public void bakePizza() { 7 | System.out.println("Pizza baked at 400 for 20 minutes."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/factoryMethod/PizzaFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | public class PizzaFactory extends BasePizzaFactory{ 4 | @Override 5 | public Pizza createPizza(String type){ 6 | Pizza pizza; 7 | switch (type.toLowerCase()) 8 | { 9 | case "cheese": 10 | pizza = new CheesePizza(); 11 | break; 12 | case "pepperoni": 13 | pizza = new PepperoniPizza(); 14 | break; 15 | case "veggie": 16 | pizza = new VeggiePizza(); 17 | break; 18 | default: throw new IllegalArgumentException("No such pizza."); 19 | } 20 | 21 | pizza.addIngredients(); 22 | pizza.bakePizza(); 23 | return pizza; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/factoryMethod/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | public class VeggiePizza extends Pizza { 4 | @Override 5 | public void addIngredients() { 6 | System.out.println("Preparing ingredients for veggie pizza."); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/flyweight/CarFactory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.flyweight; 2 | 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | public class CarFactory { 7 | private static Map flyweights = new HashMap<>(); 8 | /*If key exist, return flyweight from Map*/ 9 | public static RaceCar getRaceCar(String key) { 10 | if(flyweights.containsKey(key)){ 11 | return flyweights.get(key); 12 | } 13 | RaceCar raceCar; 14 | /*If key does not exist in Map, create flyweight, put it in Map, and return the object*/ 15 | switch (key) 16 | { 17 | case "Midget": 18 | raceCar = new FlyweightMidgetCar(); 19 | raceCar.name="Midget Car"; 20 | raceCar.speed=140; 21 | raceCar.horsePower=400; 22 | break; 23 | case "Sprint": 24 | raceCar = new FlyweightSprintCar(); 25 | raceCar.name="Sprint Car"; 26 | raceCar.speed=160; 27 | raceCar.horsePower=1000; 28 | break; 29 | default: 30 | throw new IllegalArgumentException("Unsupported car type."); 31 | } 32 | flyweights.put(key, raceCar); 33 | return raceCar; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/flyweight/FlyweightMidgetCar.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.flyweight; 2 | 3 | public class FlyweightMidgetCar extends RaceCar { 4 | /*Track number of flyweight instantiation*/ 5 | public static int num; 6 | public FlyweightMidgetCar() 7 | { 8 | num++; 9 | } 10 | /*This method accepts car location (extrinsic). No reference to current 11 | *or new location is maintained inside the flyweight implementation*/ 12 | @Override 13 | public void moveCar(int currentX, int currentY, int newX ,int newY) 14 | { 15 | System.out.println("New location of "+this.name+" is X"+newX + " - Y"+newY); 16 | } 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/flyweight/FlyweightSprintCar.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.flyweight; 2 | 3 | 4 | public class FlyweightSprintCar extends RaceCar{ 5 | /*Track number of flyweight instantiation*/ 6 | public static int num; 7 | public FlyweightSprintCar() 8 | { 9 | num++; 10 | } 11 | 12 | /*This method accepts car location (extrinsic). No reference to current 13 | *or new location is maintained inside the flyweight implementation*/ 14 | @Override 15 | public void moveCar(int currentX, int currentY, int newX ,int newY) 16 | { 17 | System.out.println("New location of "+this.name+" is X"+newX + " - Y"+newY); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/flyweight/RaceCar.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.flyweight; 2 | 3 | 4 | public abstract class RaceCar { 5 | /*Intrinsic state stored and shared in the Flyweight object*/ 6 | String name; 7 | int speed; 8 | int horsePower; 9 | /* Extrinsic state is stored or computed by client objects, and passed to the Flyweight.*/ 10 | abstract void moveCar(int currentX, int currentY, int newX ,int newY); 11 | } 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/flyweight/RaceCarClient.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.flyweight; 2 | 3 | public class RaceCarClient { 4 | private RaceCar raceCar; 5 | public RaceCarClient(String name) { 6 | /*Ask factory for a RaceCar*/ 7 | raceCar = CarFactory.getRaceCar(name); 8 | } 9 | /** 10 | * The extrinsic state of the flyweight is maintained by the client 11 | */ 12 | private int currentX = 0; 13 | private int currentY=0; 14 | public void moveCar(int newX, int newY){ 15 | /*Car movement is handled by the flyweight object*/ 16 | raceCar.moveCar(currentX, 17 | currentY, newX, newY); 18 | currentX = newX; 19 | currentY = newY; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/AdditionExpression.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | 4 | public class AdditionExpression implements Expression { 5 | private Expression firstExpression,secondExpression; 6 | public AdditionExpression(Expression firstExpression, Expression secondExpression){ 7 | this.firstExpression=firstExpression; 8 | this.secondExpression=secondExpression; 9 | } 10 | @Override 11 | public int interpret(){ 12 | return this.firstExpression.interpret()+this.secondExpression.interpret(); 13 | } 14 | @Override 15 | public String toString(){ 16 | return "+"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/Expression.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | 4 | public interface Expression { 5 | int interpret(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/ExpressionParser.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | 4 | import java.util.Stack; 5 | 6 | public class ExpressionParser { 7 | Stack stack=new Stack<>(); 8 | public int parse(String str){ 9 | String[] tokenList = str.split(" "); 10 | for (String symbol : tokenList) { 11 | if (!ParserUtil.isOperator(symbol)) { 12 | Expression numberExpression = new NumberExpression(symbol); 13 | stack.push(numberExpression); 14 | System.out.println(String.format("Pushed to stack: %d", numberExpression.interpret())); 15 | 16 | } else if (ParserUtil.isOperator(symbol)) { 17 | Expression firstExpression = stack.pop(); 18 | Expression secondExpression = stack.pop(); 19 | System.out.println(String.format("Popped operands %d and %d", 20 | firstExpression.interpret(), secondExpression.interpret())); 21 | Expression operator = ParserUtil.getExpressionObject(firstExpression, secondExpression, symbol); 22 | System.out.println(String.format("Applying Operator: %s", operator)); 23 | int result = operator.interpret(); 24 | NumberExpression resultExpression = new NumberExpression(result); 25 | stack.push(resultExpression); 26 | System.out.println(String.format("Pushed result to stack: %d", resultExpression.interpret())); 27 | } 28 | } 29 | int result= stack.pop().interpret(); 30 | return result; 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/MultiplicationExpression.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | 4 | public class MultiplicationExpression implements Expression{ 5 | private Expression firstExpression,secondExpression; 6 | public MultiplicationExpression(Expression firstExpression, Expression secondExpression){ 7 | this.firstExpression=firstExpression; 8 | this.secondExpression=secondExpression; 9 | } 10 | @Override 11 | public int interpret(){ 12 | return this.firstExpression.interpret()*this.secondExpression.interpret(); 13 | } 14 | @Override 15 | public String toString(){ 16 | return "*"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/NumberExpression.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | 4 | public class NumberExpression implements Expression{ 5 | private int number; 6 | public NumberExpression(int number){ 7 | this.number=number; 8 | } 9 | public NumberExpression(String number){ 10 | this.number=Integer.parseInt(number); 11 | } 12 | @Override 13 | public int interpret(){ 14 | return this.number; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/ParserUtil.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | public class ParserUtil { 4 | public static boolean isOperator(String symbol) { 5 | return (symbol.equals("+") || symbol.equals("-") || symbol.equals("*")); 6 | 7 | } 8 | public static Expression getExpressionObject(Expression firstExpression,Expression secondExpression,String symbol){ 9 | if(symbol.equals("+")) 10 | return new AdditionExpression(firstExpression,secondExpression); 11 | else if(symbol.equals("-")) 12 | return new SubtractionExpression(firstExpression,secondExpression); 13 | else 14 | return new MultiplicationExpression(firstExpression,secondExpression); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/interpreter/SubtractionExpression.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | 4 | public class SubtractionExpression implements Expression{ 5 | private Expression firstExpression,secondExpression; 6 | public SubtractionExpression(Expression firstExpression, Expression secondExpression){ 7 | this.firstExpression=firstExpression; 8 | this.secondExpression=secondExpression; 9 | } 10 | @Override 11 | public int interpret(){ 12 | return this.firstExpression.interpret()-this.secondExpression.interpret(); 13 | } 14 | @Override 15 | public String toString(){ 16 | return "-"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/iterator/DesignPattern.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.iterator; 2 | 3 | public class DesignPattern { 4 | private String patternType; 5 | private String patternName; 6 | public DesignPattern(String patternType, String patternName){ 7 | this.patternType=patternType; 8 | this.patternName=patternName; 9 | } 10 | 11 | public String getPatternType() { 12 | 13 | return patternType; 14 | } 15 | 16 | public String getPatternName() { 17 | return patternName; 18 | } 19 | 20 | 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/iterator/PatternAggregate.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.iterator; 2 | 3 | public interface PatternAggregate { 4 | void addPattern(DesignPattern designPattern); 5 | void removePattern(DesignPattern designPattern); 6 | PatternIterator getPatternIterator(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/iterator/PatternAggregateImpl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.iterator; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class PatternAggregateImpl implements PatternAggregate{ 8 | List patternList; 9 | public PatternAggregateImpl(){ 10 | patternList=new ArrayList(); 11 | } 12 | @Override 13 | public void addPattern(DesignPattern designPattern){ 14 | patternList.add(designPattern); 15 | } 16 | 17 | @Override 18 | public void removePattern(DesignPattern designPattern){ 19 | patternList.remove(designPattern); 20 | } 21 | 22 | @Override 23 | public PatternIterator getPatternIterator(){ 24 | return new PatternIteratorImpl(patternList); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/iterator/PatternIterator.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.iterator; 2 | 3 | 4 | public interface PatternIterator { 5 | DesignPattern nextPattern(); 6 | boolean isLastPattern(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/iterator/PatternIteratorImpl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.iterator; 2 | 3 | 4 | import java.util.List; 5 | 6 | public class PatternIteratorImpl implements PatternIterator{ 7 | public List patternList; 8 | int position; 9 | DesignPattern designPattern; 10 | public PatternIteratorImpl(List patternList){ 11 | this.patternList=patternList; 12 | } 13 | @Override 14 | public DesignPattern nextPattern(){ 15 | System.out.println("Returning pattern at Position: "+position); 16 | designPattern=(DesignPattern)patternList.get(position); 17 | position++; 18 | return designPattern; 19 | } 20 | @Override 21 | public boolean isLastPattern(){ 22 | if(position< patternList.size()){ 23 | return false; 24 | } 25 | return true; 26 | } 27 | 28 | 29 | } -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/mediator/colleague/ArmedUnit.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.mediator.colleague; 2 | 3 | 4 | public interface ArmedUnit { 5 | void attack(); 6 | void stopAttack(); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/mediator/colleague/SoldierUnit.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.mediator.colleague; 2 | 3 | 4 | import guru.springframework.gof.mediator.mediator.Commander; 5 | 6 | public class SoldierUnit implements ArmedUnit{ 7 | 8 | private Commander commander; 9 | public SoldierUnit(Commander commander){ 10 | this.commander=commander; 11 | } 12 | @Override 13 | public void attack() 14 | { 15 | if(commander.canAttack()) 16 | { 17 | System.out.println("SoldierUnit: Attacking....."); 18 | commander.setAttackStatus(false); 19 | } 20 | else{ 21 | System.out.println("SoldierUnit: Cannot attack now. Other units attacking...."); 22 | } 23 | } 24 | @Override 25 | public void stopAttack(){ 26 | System.out.println("SoldierUnit: Stopped Attacking....."); 27 | commander.setAttackStatus(true); 28 | } 29 | 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/mediator/colleague/TankUnit.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.mediator.colleague; 2 | 3 | import guru.springframework.gof.mediator.mediator.Commander; 4 | 5 | public class TankUnit implements ArmedUnit{ 6 | private Commander commander; 7 | public TankUnit(Commander commander){ 8 | this.commander=commander; 9 | } 10 | @Override 11 | public void attack() 12 | { 13 | if(commander.canAttack()) 14 | { 15 | System.out.println("TankUnit: Attacking....."); 16 | commander.setAttackStatus(false); 17 | } 18 | else{ 19 | System.out.println("TankUnit: Cannot attack now. Other units attacking...."); 20 | } 21 | } 22 | @Override 23 | public void stopAttack(){ 24 | System.out.println("TankUnit: Stopped attacking....."); 25 | commander.setAttackStatus(true); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/mediator/mediator/Commander.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.mediator.mediator; 2 | 3 | 4 | import guru.springframework.gof.mediator.colleague.ArmedUnit; 5 | import guru.springframework.gof.mediator.colleague.SoldierUnit; 6 | import guru.springframework.gof.mediator.colleague.TankUnit; 7 | 8 | public interface Commander { 9 | void registerArmedUnits(ArmedUnit soldierUnit, ArmedUnit tankUnit); 10 | void setAttackStatus(boolean attackStatus); 11 | boolean canAttack(); 12 | void startAttack(ArmedUnit armedUnit); 13 | void ceaseAttack(ArmedUnit armedUnit); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/mediator/mediator/CommanderImpl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.mediator.mediator; 2 | 3 | 4 | import guru.springframework.gof.mediator.colleague.ArmedUnit; 5 | import guru.springframework.gof.mediator.colleague.SoldierUnit; 6 | import guru.springframework.gof.mediator.colleague.TankUnit; 7 | 8 | public class CommanderImpl implements Commander { 9 | ArmedUnit soldierUnit, tankUnit; 10 | boolean attackStatus = true; 11 | 12 | @Override 13 | public void registerArmedUnits(ArmedUnit soldierUnit, ArmedUnit tankUnit) { 14 | this.soldierUnit = soldierUnit; 15 | this.tankUnit = tankUnit; 16 | } 17 | 18 | @Override 19 | public void setAttackStatus(boolean attackStatus) { 20 | this.attackStatus = attackStatus; 21 | } 22 | 23 | @Override 24 | public boolean canAttack() { 25 | return attackStatus; 26 | } 27 | @Override 28 | public void startAttack(ArmedUnit armedUnit) { 29 | armedUnit.attack(); 30 | } 31 | @Override 32 | public void ceaseAttack(ArmedUnit armedUnit) { 33 | armedUnit.stopAttack(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/memento/EmpCaretaker.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.memento; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | import java.util.Stack; 6 | 7 | public class EmpCaretaker { 8 | 9 | 10 | final Deque mementos = new ArrayDeque<>(); 11 | public EmpMemento getMemento() 12 | { 13 | 14 | EmpMemento empMemento= mementos.pop(); 15 | return empMemento; 16 | } 17 | 18 | public void addMemento(EmpMemento memento) 19 | { 20 | mementos.push(memento); 21 | 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/memento/EmpMemento.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.memento; 2 | 3 | public class EmpMemento { 4 | private int empId; 5 | private String empName; 6 | private String empPhoneNo; 7 | private String empDesignation; 8 | public EmpMemento(int empId,String empName,String empPhoneNo,String empDesignation) { 9 | this.empId = empId; 10 | this.empName = empName; 11 | this.empPhoneNo = empPhoneNo; 12 | this.empDesignation = empDesignation; 13 | } 14 | public int getEmpId() { 15 | return empId; 16 | } 17 | 18 | public String getEmpName() { 19 | return empName; 20 | } 21 | 22 | public String getEmpDesignation() { 23 | return empDesignation; 24 | } 25 | 26 | public String getEmpPhoneNo() { 27 | return empPhoneNo; 28 | } 29 | 30 | @Override 31 | public String toString(){ 32 | String str="Current Memento State" + this.empId +" , "+this.empName +" , "+this.getEmpPhoneNo()+" , "+this.getEmpDesignation(); 33 | return str; 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/memento/EmpOriginator.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.memento; 2 | 3 | 4 | public class EmpOriginator { 5 | private int empId; 6 | private String empName; 7 | private String empPhoneNo; 8 | private String empDesignation; 9 | 10 | public EmpOriginator(int empId, String empName, String empPhoneNo,String empDesignation) 11 | { 12 | this.empId=empId; 13 | this.empName=empName; 14 | this.empPhoneNo=empPhoneNo; 15 | this.empDesignation=empDesignation; 16 | } 17 | 18 | public int getEmpId() { 19 | return empId; 20 | } 21 | 22 | public void setEmpId(int empId) { 23 | this.empId = empId; 24 | } 25 | 26 | public String getEmpName() { 27 | return empName; 28 | } 29 | 30 | public void setEmpName(String empName) { 31 | this.empName = empName; 32 | } 33 | 34 | public String getEmpPhoneNo() { 35 | return empPhoneNo; 36 | } 37 | 38 | public void setEmpPhoneNo(String empPhoneNo) { 39 | this.empPhoneNo = empPhoneNo; 40 | } 41 | 42 | public String getEmpDesignation() { 43 | return empDesignation; 44 | } 45 | 46 | public void setEmpDesignation(String empDesignation) { 47 | this.empDesignation = empDesignation; 48 | } 49 | 50 | public EmpMemento saveToMemento() { 51 | 52 | EmpMemento empMemento=new EmpMemento(this.empId, this.empName, this.empPhoneNo, this.empDesignation ); 53 | return empMemento; 54 | } 55 | public void undoFromMemento(EmpMemento memento) 56 | { 57 | 58 | this.empId = memento.getEmpId(); 59 | this.empName = memento.getEmpName(); 60 | this.empPhoneNo = memento.getEmpPhoneNo(); 61 | this.empDesignation = memento.getEmpDesignation(); 62 | } 63 | 64 | public void printInfo() 65 | { 66 | System.out.println("ID: "+ this.empId); 67 | System.out.println("Name: "+ this.empName); 68 | System.out.println("Phone Number: "+ this.empPhoneNo); 69 | System.out.println("Designation: "+ this.empDesignation); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/observer/javaapi/Bidder.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.javaapi; 2 | 3 | 4 | import java.util.Observable; 5 | import java.util.Observer; 6 | 7 | public class Bidder implements Observer { 8 | Product observable; 9 | String bidderName; 10 | public Bidder(String bidderName) { 11 | this.bidderName = bidderName; 12 | } 13 | 14 | @Override 15 | public void update(Observable observable, Object arg){ 16 | this.observable = (Product) observable; 17 | String name = this.observable.getObserver().toString(); 18 | if(name.equals(bidderName)) 19 | { 20 | System.out.println("Hello "+bidderName+"! New bid of amount "+this.observable.getBidAmount()+" has been placed on "+this.observable.getProductName()+" by you"); 21 | } 22 | if (!name.equals(bidderName)) 23 | System.out.println("Hello "+bidderName+"! New bid of amount "+this.observable.getBidAmount()+" has been placed on "+this.observable.getProductName()+" by "+this.observable.getObserver()); 24 | } 25 | 26 | @Override 27 | public String toString() 28 | { 29 | return bidderName; 30 | } 31 | 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/observer/javaapi/Product.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.javaapi; 2 | 3 | 4 | import java.util.Observable; 5 | import java.util.Observer; 6 | import java.math.BigDecimal; 7 | 8 | public class Product extends Observable{ 9 | private String productName; 10 | private BigDecimal bidAmount; 11 | private Observer observer; 12 | public Observer getObserver() { 13 | return observer; 14 | } 15 | public BigDecimal getBidAmount() { 16 | return bidAmount; 17 | } 18 | public String getProductName() { 19 | return productName; 20 | } 21 | 22 | public Product(String productName, BigDecimal bidAmount){ 23 | this.productName=productName; 24 | this.bidAmount=bidAmount; 25 | } 26 | 27 | public void setBidAmount(Observer observer,BigDecimal newBidAmount){ 28 | System.out.println("-----------------New bid placed----------------"); 29 | int res=bidAmount.compareTo(newBidAmount); 30 | if(res==-1){ 31 | this.observer=observer; 32 | this.bidAmount=newBidAmount; 33 | setChanged(); 34 | notifyObservers(); 35 | } 36 | else { 37 | System.out.println("New bid amount cannot be less or equal to current bid amount: "+this.bidAmount); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/observer/observerimpl/Bidder.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.observerimpl; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class Bidder implements Observer{ 6 | String bidderName; 7 | public Bidder(String bidderName) { 8 | this.bidderName = bidderName; 9 | } 10 | 11 | @Override 12 | public void update(Observer observer,String productName, BigDecimal bidAmount){ 13 | if(observer.toString().equals(bidderName)){ 14 | System.out.println("Hello "+bidderName+"! New bid of amount "+bidAmount+" has been placed on "+productName+" by you"); 15 | } 16 | if(!observer.toString().equals(bidderName)) { 17 | System.out.println("Hello " + bidderName + "! New bid of amount " + bidAmount + " has been placed on " + productName + " by " + observer); 18 | } 19 | } 20 | 21 | @Override 22 | public String toString(){ 23 | return bidderName; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/observer/observerimpl/Observer.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.observerimpl; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public interface Observer { 6 | public void update(Observer observer,String productName, BigDecimal bidAmount); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/observer/observerimpl/Product.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.observerimpl; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.ArrayList; 5 | 6 | public class Product implements Subject{ 7 | private ArrayList observers = new ArrayList<>(); 8 | private String productName; 9 | private BigDecimal bidAmount; 10 | private Observer observer; 11 | 12 | public Product(String productName, BigDecimal bidAmount){ 13 | this.productName=productName; 14 | this.bidAmount=bidAmount; 15 | } 16 | 17 | @Override 18 | public void setBidAmount(Observer observer,BigDecimal newBidAmount){ 19 | int res=bidAmount.compareTo(newBidAmount); 20 | if(res==-1){ 21 | this.observer=observer; 22 | this.bidAmount=newBidAmount; 23 | notifyObservers(); 24 | } 25 | else { 26 | System.out.println("New bid amount cannot be less or equal to current bid amount: "+this.bidAmount); 27 | } 28 | } 29 | 30 | @Override 31 | public void registerObserver(Observer observer) { 32 | observers.add(observer); 33 | } 34 | @Override 35 | public void removeObserver(Observer observer) { 36 | observers.remove(observer); 37 | System.out.println("-----------------"+observer+" has withdrawn from bidding----------------"); 38 | } 39 | 40 | @Override 41 | public void notifyObservers() { 42 | System.out.println("-----------------New bid placed----------------"); 43 | for (Observer ob : observers) { 44 | ob.update(this.observer,this.productName,this.bidAmount ); 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/observer/observerimpl/Subject.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.observerimpl; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public interface Subject { 6 | public void registerObserver(Observer observer); 7 | public void removeObserver(Observer observer); 8 | public void notifyObservers(); 9 | public void setBidAmount(Observer observer,BigDecimal newBidAmount); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/prototype/AuthorizedSignatory.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.prototype; 2 | 3 | /** 4 | * Created by Admin on 4/21/2015. 5 | */ 6 | public class AuthorizedSignatory implements Cloneable { 7 | private String name; 8 | private String designation; 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void setName(String name) { 15 | this.name = name; 16 | } 17 | 18 | public String getDesignation() { 19 | return designation; 20 | } 21 | 22 | public void setDesignation(String designation) { 23 | this.designation = designation; 24 | } 25 | 26 | @Override 27 | protected Object clone() throws CloneNotSupportedException { 28 | return super.clone(); 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "[AuthorizedSignatory: Name - " + getName() + ", Designation - " + getDesignation() + "]"; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/prototype/DocumentPrototypeManager.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.prototype; 2 | 3 | /** 4 | * Created by Admin on 4/21/2015. 5 | */ 6 | public class DocumentPrototypeManager { 7 | private static java.util.Map prototypes = new java.util.HashMap(); 8 | 9 | static { 10 | TAndC tAndC = new TAndC(); 11 | tAndC.setVendorName("Vendor Name Placeholder"); 12 | /*Retrieve Terms and Conditions from database/network call/disk I/O here*/ 13 | tAndC.setContent("Please read and accept the terms and conditions..."); 14 | prototypes.put("tandc", tAndC); 15 | AuthorizedSignatory authorizedSignatory = new AuthorizedSignatory(); 16 | authorizedSignatory.setName("Andrew Clark"); 17 | authorizedSignatory.setDesignation("Operation Head"); 18 | NDAgreement nda = new NDAgreement(); 19 | nda.setVendorName("Vendor Name Placeholder"); 20 | /*Retrieve Non Disclosure Agreement from database/network call/disk I/O here*/ 21 | nda.setContent("Please read and accept the NDA..."); 22 | nda.setAuthorizedSignatory(authorizedSignatory); 23 | prototypes.put("nda", nda); 24 | } 25 | 26 | public static PrototypeCapableDocument getClonedDocument(final String type) { 27 | PrototypeCapableDocument clonedDoc = null; 28 | try { 29 | PrototypeCapableDocument doc = prototypes.get(type); 30 | clonedDoc = doc.cloneDocument(); 31 | } catch (CloneNotSupportedException e) { 32 | e.printStackTrace(); 33 | } 34 | return clonedDoc; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/prototype/NDAgreement.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.prototype; 2 | 3 | /** 4 | * Created by Admin on 4/21/2015. 5 | */ 6 | public class NDAgreement extends PrototypeCapableDocument { 7 | private AuthorizedSignatory authorizedSignatory; 8 | 9 | public AuthorizedSignatory getAuthorizedSignatory() { 10 | return authorizedSignatory; 11 | } 12 | 13 | public void setAuthorizedSignatory(AuthorizedSignatory authorizedSignatory) { 14 | this.authorizedSignatory = authorizedSignatory; 15 | } 16 | 17 | @Override 18 | public PrototypeCapableDocument cloneDocument() throws CloneNotSupportedException { 19 | /*Clone with deep copy*/ 20 | NDAgreement nda; 21 | nda = (NDAgreement) super.clone(); 22 | AuthorizedSignatory clonedAuthorizedSignatory = (AuthorizedSignatory) nda.getAuthorizedSignatory().clone(); 23 | nda.setAuthorizedSignatory(clonedAuthorizedSignatory); 24 | return nda; 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | return "[NDAgreement: Vendor Name - " + getVendorName() + ", Content - " + getContent() + ", Authorized Signatory - " + getAuthorizedSignatory() + "]"; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/prototype/PrototypeCapableDocument.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.prototype; 2 | 3 | /** 4 | * Created by Admin on 4/21/2015. 5 | */ 6 | public abstract class PrototypeCapableDocument implements Cloneable { 7 | private String vendorName; 8 | private String content; 9 | 10 | public String getVendorName() { 11 | return vendorName; 12 | } 13 | 14 | public void setVendorName(String vendorName) { 15 | this.vendorName = vendorName; 16 | } 17 | 18 | public String getContent() { 19 | return content; 20 | } 21 | 22 | public void setContent(String content) { 23 | this.content = content; 24 | } 25 | 26 | public abstract PrototypeCapableDocument cloneDocument() throws CloneNotSupportedException; 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/prototype/TAndC.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.prototype; 2 | 3 | /** 4 | * Created by Admin on 4/21/2015. 5 | */ 6 | public class TAndC extends PrototypeCapableDocument { 7 | 8 | @Override 9 | public PrototypeCapableDocument cloneDocument() { 10 | /*Clone with shallow copy*/ 11 | TAndC tAndC = null; 12 | try { 13 | tAndC = (TAndC) super.clone(); 14 | } catch (CloneNotSupportedException e) { 15 | e.printStackTrace(); 16 | } 17 | return tAndC; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return "[TAndC: Vendor Name - " + getVendorName() + ", Content - " + getContent() + "]"; 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/proxy/ReportGenerator.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.proxy; 2 | 3 | public interface ReportGenerator { 4 | void displayReportTemplate(String reportFormat,int reportEntries); 5 | void generateComplexReport(String reportFormat,int reportEntries); 6 | void generateSensitiveReport(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/proxy/ReportGeneratorImpl.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.proxy; 2 | 3 | public class ReportGeneratorImpl implements ReportGenerator { 4 | 5 | public ReportGeneratorImpl(){ 6 | System.out.println("ReportGeneratorImpl instance created"); 7 | } 8 | @Override 9 | public void displayReportTemplate(String reportFormat,int reportEntries) { 10 | 11 | } 12 | @Override 13 | public void generateComplexReport(String reportFormat, int reportEntries){ 14 | System.out.println("ReportGeneratorImpl: Generating complex report in "+reportFormat+" format with "+ reportEntries+" entries"); 15 | 16 | } 17 | @Override 18 | public void generateSensitiveReport(){ 19 | System.out.println("ReportGeneratorImpl: Generating sensitive report"); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/proxy/ReportGeneratorImplProxy.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.proxy; 2 | 3 | 4 | public class ReportGeneratorImplProxy implements ReportGenerator{ 5 | ReportGenerator reportGeneratorImpl; 6 | private Role accessRole; 7 | public ReportGeneratorImplProxy(Role accessRole){ 8 | this.accessRole=accessRole; 9 | } 10 | 11 | @Override 12 | public void displayReportTemplate(String reportFormat,int reportEntries) { 13 | System.out.println("ReportGeneratorImplProxy: Displaying blank report template in " + reportFormat + " format with " + reportEntries + " entries"); 14 | } 15 | 16 | @Override 17 | public void generateComplexReport(String reportFormat,int reportEntries){ 18 | if(reportGeneratorImpl==null) 19 | reportGeneratorImpl = new ReportGeneratorImpl(); 20 | reportGeneratorImpl.generateComplexReport(reportFormat,reportEntries); 21 | } 22 | @Override 23 | public void generateSensitiveReport(){ 24 | if(accessRole.getRole().equals("Manager")){ 25 | if(reportGeneratorImpl==null) 26 | reportGeneratorImpl = new ReportGeneratorImpl(); 27 | reportGeneratorImpl.generateSensitiveReport(); 28 | } 29 | else{ 30 | System.out.println("You are not authorized to access sensitive reports."); 31 | } 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/proxy/Role.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.proxy; 2 | 3 | 4 | public class Role { 5 | private String role; 6 | public String getRole() { 7 | return role; 8 | } 9 | public void setRole(String role) { 10 | this.role = role; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/state/context/CandyVendingMachine.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.context; 2 | 3 | 4 | import guru.springframework.gof.state.states.*; 5 | 6 | public class CandyVendingMachine { 7 | 8 | CandyVendingMachineState noCoinState; 9 | CandyVendingMachineState noCandyState; 10 | CandyVendingMachineState dispensedState; 11 | CandyVendingMachineState containsCoinState; 12 | CandyVendingMachineState state; 13 | int count; 14 | 15 | public CandyVendingMachine(int numberOfCandies){ 16 | count=numberOfCandies; 17 | noCoinState=new NoCoinState(this); 18 | noCandyState=new NoCandyState(this); 19 | dispensedState=new DispensedState(this); 20 | containsCoinState=new ContainsCoinState(this); 21 | state = noCoinState; 22 | } 23 | 24 | public void refillCandy(int count){ 25 | this.count+=count; 26 | this.state=noCoinState; 27 | } 28 | 29 | public void ejectCandy(){ 30 | if(count!=0){ 31 | count--; 32 | } 33 | } 34 | 35 | public void insertCoin(){ 36 | System.out.println("You inserted a coin."); 37 | state.insertCoin(); 38 | } 39 | 40 | public void pressButton(){ 41 | System.out.println("You have pressed the button."); 42 | state.pressButton(); 43 | state.dispense(); 44 | } 45 | 46 | public CandyVendingMachineState getNoCandyState() { 47 | return noCandyState; 48 | } 49 | 50 | public void setNoCandyState(CandyVendingMachineState noCandyState) { 51 | this.noCandyState = noCandyState; 52 | } 53 | 54 | public CandyVendingMachineState getNoCoinState() { 55 | return noCoinState; 56 | } 57 | 58 | public void setNoCoinState(CandyVendingMachineState noCoinState) { 59 | this.noCoinState = noCoinState; 60 | } 61 | 62 | public int getCount() { 63 | return count; 64 | } 65 | 66 | public void setCount(int count) { 67 | this.count = count; 68 | } 69 | 70 | public CandyVendingMachineState getState() { 71 | return state; 72 | } 73 | 74 | public void setState(CandyVendingMachineState state) { 75 | this.state = state; 76 | } 77 | 78 | public CandyVendingMachineState getContainsCoinState() { 79 | return containsCoinState; 80 | } 81 | 82 | public void setContainsCoinState(CandyVendingMachineState containsCoinState) { 83 | this.containsCoinState = containsCoinState; 84 | } 85 | 86 | public CandyVendingMachineState getDispensedState() { 87 | return dispensedState; 88 | } 89 | 90 | public void setDispensedState(CandyVendingMachineState dispensedState) { 91 | this.dispensedState = dispensedState; 92 | } 93 | @Override 94 | public String toString(){ 95 | String machineDef="Current state of machine "+state +". Candies available "+count; 96 | return machineDef; 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/state/states/CandyVendingMachineState.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.states; 2 | 3 | public interface CandyVendingMachineState { 4 | void insertCoin(); 5 | void pressButton(); 6 | void dispense(); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/state/states/ContainsCoinState.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.states; 2 | 3 | 4 | import guru.springframework.gof.state.context.CandyVendingMachine; 5 | 6 | public class ContainsCoinState implements CandyVendingMachineState{ 7 | 8 | CandyVendingMachine machine; 9 | 10 | public ContainsCoinState(CandyVendingMachine machine){ 11 | this.machine=machine; 12 | } 13 | 14 | @Override 15 | public void insertCoin() { 16 | System.out.println("Coin already inserted"); 17 | } 18 | @Override 19 | public void pressButton() { 20 | machine.setState(machine.getDispensedState()); 21 | } 22 | @Override 23 | public void dispense() { 24 | System.out.println("Press button to dispense"); 25 | } 26 | @Override 27 | public String toString(){ 28 | return "ContainsCoinState"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/state/states/DispensedState.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.states; 2 | 3 | import guru.springframework.gof.state.context.CandyVendingMachine; 4 | 5 | public class DispensedState implements CandyVendingMachineState{ 6 | 7 | CandyVendingMachine machine; 8 | public DispensedState(CandyVendingMachine machine){ 9 | this.machine=machine; 10 | } 11 | @Override 12 | public void insertCoin() { 13 | System.out.println("Error. System is currently dispensing"); 14 | } 15 | @Override 16 | public void pressButton() { 17 | System.out.println("Error. System is currently dispensing"); 18 | } 19 | @Override 20 | public void dispense() { 21 | if(machine.getCount()>0) { 22 | machine.setState(machine.getNoCoinState()); 23 | machine.setCount(machine.getCount()-1); 24 | } 25 | else{ 26 | System.out.println("No candies available"); 27 | machine.setState(machine.getNoCandyState()); 28 | } 29 | } 30 | @Override 31 | public String toString(){ 32 | return "DispensedState"; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/state/states/NoCandyState.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.states; 2 | 3 | 4 | import guru.springframework.gof.state.context.CandyVendingMachine; 5 | 6 | public class NoCandyState implements CandyVendingMachineState{ 7 | 8 | CandyVendingMachine machine; 9 | public NoCandyState(CandyVendingMachine machine){ 10 | this.machine=machine; 11 | } 12 | @Override 13 | public void insertCoin() { 14 | System.out.println("No candies available"); 15 | } 16 | @Override 17 | public void pressButton() { 18 | System.out.println("No candies available"); 19 | } 20 | @Override 21 | public void dispense() { 22 | System.out.println("No candies available"); 23 | } 24 | @Override 25 | public String toString(){ 26 | return "NoCandyState"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/state/states/NoCoinState.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.states; 2 | 3 | 4 | import guru.springframework.gof.state.context.CandyVendingMachine; 5 | 6 | public class NoCoinState implements CandyVendingMachineState{ 7 | 8 | CandyVendingMachine machine; 9 | public NoCoinState(CandyVendingMachine machine){ 10 | this.machine=machine; 11 | } 12 | @Override 13 | public void insertCoin() { 14 | machine.setState(machine.getContainsCoinState()); 15 | } 16 | @Override 17 | public void pressButton() { 18 | System.out.println("No coin inserted"); 19 | } 20 | @Override 21 | public void dispense() { 22 | System.out.println("No coin inserted"); 23 | } 24 | @Override 25 | public String toString(){ 26 | return "NoCoinState"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/strategy/context/Encryptor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.strategy.context; 2 | 3 | 4 | import guru.springframework.gof.strategy.strategies.EncryptionStrategy; 5 | 6 | public class Encryptor { 7 | private EncryptionStrategy strategy; 8 | private String plainText; 9 | public Encryptor(EncryptionStrategy strategy){ 10 | this.strategy=strategy; 11 | } 12 | public void encrypt(){ 13 | strategy.encryptData(plainText); 14 | } 15 | public String getPlainText() { 16 | return plainText; 17 | } 18 | 19 | public void setPlainText(String plainText) { 20 | this.plainText = plainText; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/strategy/strategies/AesEncryptionStrategy.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.strategy.strategies; 2 | 3 | import javax.crypto.Cipher; 4 | import javax.crypto.KeyGenerator; 5 | import javax.crypto.SecretKey; 6 | 7 | public class AesEncryptionStrategy implements EncryptionStrategy{ 8 | 9 | @Override 10 | public void encryptData(String plaintext) { 11 | System.out.println("-------Encrypting data using AES algorithm-------"); 12 | try { 13 | KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); 14 | keyGenerator.init(128); 15 | SecretKey secretKey = keyGenerator.generateKey(); 16 | byte[] plaintTextByteArray = plaintext.getBytes("UTF8"); 17 | 18 | Cipher cipher = Cipher.getInstance("AES"); 19 | cipher.init(Cipher.ENCRYPT_MODE, secretKey); 20 | byte[] cipherText = cipher.doFinal(plaintTextByteArray); 21 | 22 | System.out.println("Original data: " + plaintext); 23 | System.out.println("Encrypted data:"); 24 | for (int i = 0; i < cipherText.length; i++) { 25 | System.out.print(cipherText[i] + " "); 26 | 27 | } 28 | } 29 | catch(Exception ex){ 30 | ex.printStackTrace(); 31 | } 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/strategy/strategies/BlowfishEncryptionStrategy.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.strategy.strategies; 2 | 3 | import javax.crypto.Cipher; 4 | import javax.crypto.KeyGenerator; 5 | import javax.crypto.SecretKey; 6 | 7 | public class BlowfishEncryptionStrategy implements EncryptionStrategy{ 8 | @Override 9 | public void encryptData(String plaintext) { 10 | System.out.println("\n-------Encrypting data using Blowfish algorithm-------"); 11 | try { 12 | KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish"); 13 | keyGenerator.init(128); 14 | SecretKey secretKey = keyGenerator.generateKey(); 15 | byte[] plaintTextByteArray = plaintext.getBytes("UTF8"); 16 | 17 | Cipher cipher = Cipher.getInstance("Blowfish"); 18 | cipher.init(Cipher.ENCRYPT_MODE, secretKey); 19 | byte[] cipherText = cipher.doFinal(plaintTextByteArray); 20 | 21 | System.out.println("Original data: " + plaintext); 22 | System.out.println("Encrypted data:"); 23 | for (int i = 0; i < cipherText.length; i++) { 24 | System.out.print(cipherText[i] + " "); 25 | 26 | } 27 | } 28 | catch(Exception ex){ 29 | ex.printStackTrace(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/strategy/strategies/EncryptionStrategy.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.strategy.strategies; 2 | 3 | public interface EncryptionStrategy { 4 | void encryptData(String plainText); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/templatemethod/InHouseAssortedPizzaMaker.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.templatemethod; 2 | 3 | 4 | public class InHouseAssortedPizzaMaker extends PizzaMaker { 5 | @Override 6 | public void prepareIngredients() { 7 | System.out.println("Preparing sweet corns,chicken sausage, green chillies, and onions."); 8 | } 9 | 10 | @Override 11 | public void addToppings() { 12 | System.out.println("Adding cheddar cheese and bechamel sauce along with ingredients to crust."); 13 | } 14 | 15 | @Override 16 | public boolean customerWantsPackedPizza() { 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/templatemethod/NonVegPizzaMaker.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.templatemethod; 2 | 3 | public class NonVegPizzaMaker extends PizzaMaker { 4 | @Override 5 | public void prepareIngredients() { 6 | System.out.println("Preparing chicken ham, onion, chicken sausages, and smoked chicken"); 7 | } 8 | 9 | @Override 10 | public void addToppings() { 11 | System.out.println("Adding cheese, pepper jelly, and BBQ sauce along with ingredients to crust."); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/templatemethod/PizzaMaker.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.templatemethod; 2 | 3 | public abstract class PizzaMaker { 4 | public void makePizza() { 5 | preparePizzaDough(); 6 | preBakeCrust(); 7 | prepareIngredients(); 8 | addToppings(); 9 | bakePizza(); 10 | if (customerWantsPackedPizza()) { 11 | packPizza(); 12 | } 13 | } 14 | 15 | final void preparePizzaDough() { 16 | System.out.println("Preparing pizza dough with plain flour, dried yeast, caster sugar, salt, olive oil, and warm water."); 17 | } 18 | 19 | final void preBakeCrust() { 20 | System.out.println("Pre baking crust at 325 F for 3 minutes."); 21 | } 22 | 23 | abstract void prepareIngredients(); 24 | 25 | abstract void addToppings(); 26 | 27 | void bakePizza() { 28 | System.out.println("Baking pizza at 400 F for 12 minutes."); 29 | } 30 | 31 | void packPizza() { 32 | System.out.println("Packing pizza in pizza delivery box."); 33 | } 34 | 35 | boolean customerWantsPackedPizza() { 36 | return true; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/templatemethod/VegPizzaMaker.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.templatemethod; 2 | 3 | public class VegPizzaMaker extends PizzaMaker { 4 | @Override 5 | public void prepareIngredients() { 6 | System.out.println("Preparing mushroom, tomato slices, onions, and fresh basil leaves."); 7 | } 8 | 9 | @Override 10 | public void addToppings() { 11 | System.out.println("Adding mozzerella cheese and tomato sauce along with ingredients to crust."); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/structure/MailClient.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.structure; 2 | 3 | import guru.springframework.gof.visitor.visitors.MailClientVisitor; 4 | 5 | public interface MailClient { 6 | void sendMail(String[] mailInfo); 7 | void receiveMail(String[] mailInfo); 8 | boolean accept(MailClientVisitor visitor); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/structure/OperaMailClient.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.structure; 2 | 3 | import guru.springframework.gof.visitor.visitors.MailClientVisitor; 4 | 5 | public class OperaMailClient implements MailClient{ 6 | @Override 7 | public void sendMail(String[] mailInfo) { 8 | System.out.println(" OperaMailClient: Sending mail"); 9 | } 10 | 11 | @Override 12 | public void receiveMail(String[] mailInfo) { 13 | System.out.println(" OperaMailClient: Receiving mail"); 14 | } 15 | 16 | @Override 17 | public boolean accept(MailClientVisitor visitor) { 18 | visitor.visit(this); 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/structure/SquirrelMailClient.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.structure; 2 | 3 | import guru.springframework.gof.visitor.visitors.MailClientVisitor; 4 | 5 | public class SquirrelMailClient implements MailClient{ 6 | @Override 7 | public void sendMail(String[] mailInfo) { 8 | System.out.println(" SquirrelMailClient: Sending mail"); 9 | } 10 | 11 | @Override 12 | public void receiveMail(String[] mailInfo) { 13 | System.out.println(" SquirrelMailClient: Receiving mail"); 14 | } 15 | 16 | @Override 17 | public boolean accept(MailClientVisitor visitor) { 18 | visitor.visit(this); 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/structure/ZimbraMailClient.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.structure; 2 | 3 | 4 | import guru.springframework.gof.visitor.visitors.MailClientVisitor; 5 | 6 | public class ZimbraMailClient implements MailClient{ 7 | @Override 8 | public void sendMail(String[] mailInfo) { 9 | System.out.println(" ZimbraMailClient: Sending mail"); 10 | } 11 | 12 | @Override 13 | public void receiveMail(String[] mailInfo) { 14 | System.out.println(" ZimbraMailClient: Receiving mail"); 15 | } 16 | 17 | @Override 18 | public boolean accept(MailClientVisitor visitor) { 19 | visitor.visit(this); 20 | return true; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/visitors/LinuxMailClientVisitor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.visitors; 2 | 3 | 4 | import guru.springframework.gof.visitor.structure.OperaMailClient; 5 | import guru.springframework.gof.visitor.structure.SquirrelMailClient; 6 | import guru.springframework.gof.visitor.structure.ZimbraMailClient; 7 | 8 | public class LinuxMailClientVisitor implements MailClientVisitor{ 9 | @Override 10 | public void visit(OperaMailClient mailClient) { 11 | System.out.println("Configuration of Opera mail client for Linux complete"); 12 | } 13 | 14 | @Override 15 | public void visit(SquirrelMailClient mailClient) { 16 | System.out.println("Configuration of Squirrel mail client for Linux complete"); 17 | 18 | } 19 | 20 | @Override 21 | public void visit(ZimbraMailClient mailClient) { 22 | System.out.println("Configuration of Zimbra mail client for Linux complete"); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/visitors/MacMailClientVisitor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.visitors; 2 | 3 | 4 | import guru.springframework.gof.visitor.structure.OperaMailClient; 5 | import guru.springframework.gof.visitor.structure.SquirrelMailClient; 6 | import guru.springframework.gof.visitor.structure.ZimbraMailClient; 7 | 8 | public class MacMailClientVisitor implements MailClientVisitor{ 9 | @Override 10 | public void visit(OperaMailClient mailClient) { 11 | System.out.println("Configuration of Opera mail client for Mac complete"); 12 | } 13 | 14 | @Override 15 | public void visit(SquirrelMailClient mailClient) { 16 | System.out.println("Configuration of Squirrel mail client for Mac complete"); 17 | 18 | } 19 | 20 | @Override 21 | public void visit(ZimbraMailClient mailClient) { 22 | System.out.println("Configuration of Zimbra mail client for Mac complete"); 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/visitors/MailClientVisitor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.visitors; 2 | 3 | 4 | import guru.springframework.gof.visitor.structure.OperaMailClient; 5 | import guru.springframework.gof.visitor.structure.SquirrelMailClient; 6 | import guru.springframework.gof.visitor.structure.ZimbraMailClient; 7 | 8 | public interface MailClientVisitor { 9 | void visit(OperaMailClient mailClient); 10 | void visit(SquirrelMailClient mailClient); 11 | void visit(ZimbraMailClient mailClient); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/guru/springframework/gof/visitor/visitors/WindowsMailClientVisitor.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.visitors; 2 | 3 | import guru.springframework.gof.visitor.structure.OperaMailClient; 4 | import guru.springframework.gof.visitor.structure.SquirrelMailClient; 5 | import guru.springframework.gof.visitor.structure.ZimbraMailClient; 6 | 7 | public class WindowsMailClientVisitor implements MailClientVisitor{ 8 | @Override 9 | public void visit(OperaMailClient mailClient) { 10 | System.out.println("Configuration of Opera mail client for Windows complete"); 11 | } 12 | 13 | @Override 14 | public void visit(SquirrelMailClient mailClient) { 15 | System.out.println("Configuration of Squirrel mail client for Windows complete"); 16 | 17 | } 18 | 19 | @Override 20 | public void visit(ZimbraMailClient mailClient) { 21 | System.out.println("Configuration of Zimbra mail client for Windows complete"); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/springframeworkguru/gof/d4a4f8ecb79a46fa9dd43a733425354a3e19c6b2/src/main/resources/application.properties -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/ChainofResponsibility/RequestorClientTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.ChainofResponsibility; 2 | 3 | import guru.springframework.gof.ChainofResponsibility.handlers.AbstractSupportHandler; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | 9 | public class RequestorClientTest { 10 | 11 | @Test 12 | public void testGetHandlerChain() throws Exception { 13 | 14 | AbstractSupportHandler handler=RequestorClient.getHandlerChain(); 15 | handler.receiveRequest(AbstractSupportHandler.TECHNICAL, " I'm having problem with my internet connectivity."); 16 | System.out.println("............................................"); 17 | handler.receiveRequest(AbstractSupportHandler.BILLING, "Please resend my bill of this month."); 18 | System.out.println("............................................"); 19 | handler.receiveRequest(AbstractSupportHandler.GENERAL, "Please send any other plans for home users."); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/GangOfFourApplicationTests.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.SpringApplicationConfiguration; 6 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 7 | 8 | @RunWith(SpringJUnit4ClassRunner.class) 9 | @SpringApplicationConfiguration(classes = GangOfFourApplication.class) 10 | public class GangOfFourApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/abstractFactory/GourmetPizzaFactoryTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | import guru.springframework.gof.abstractFactory.product.Pizza; 4 | import org.junit.Test; 5 | 6 | public class GourmetPizzaFactoryTest { 7 | 8 | @Test 9 | public void testCreatePizza() throws Exception { 10 | BasePizzaFactory pizzaFactory=new GourmetPizzaFactory(); 11 | Pizza cheesePizza= pizzaFactory.createPizza("cheese"); 12 | Pizza veggiePizza=pizzaFactory.createPizza("veggie"); 13 | } 14 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/abstractFactory/SicilianPizzaFactoryTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.abstractFactory; 2 | 3 | import guru.springframework.gof.abstractFactory.product.Pizza; 4 | import org.junit.Test; 5 | 6 | public class SicilianPizzaFactoryTest { 7 | 8 | @Test 9 | public void testCreatePizza() throws Exception { 10 | BasePizzaFactory pizzaFactory=new SicilianPizzaFactory(); 11 | Pizza cheesePizza=pizzaFactory.createPizza("cheese"); 12 | Pizza pepperoniPizza =pizzaFactory.createPizza("pepperoni"); 13 | } 14 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/adapter/source/NewLineFormatterTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.adapter.source; 2 | 3 | import guru.springframework.gof.adapter.adaptee.CsvFormattable; 4 | import guru.springframework.gof.adapter.adaptee.CsvFormatter; 5 | import guru.springframework.gof.adapter.csvadapter.CsvAdapterImpl; 6 | import org.junit.Test; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | 11 | public class NewLineFormatterTest { 12 | @Test 13 | public void testFormatText() throws Exception { 14 | 15 | String testString=" Formatting line 1. Formatting line 2. Formatting line 3."; 16 | TextFormattable newLineFormatter=new NewLineFormatter(); 17 | String resultString = newLineFormatter.formatText(testString); 18 | System.out.println(resultString); 19 | 20 | CsvFormattable csvFormatter=new CsvFormatter(); 21 | TextFormattable csvAdapter=new CsvAdapterImpl(csvFormatter); 22 | String resultCsvString=csvAdapter.formatText(testString); 23 | System.out.println(resultCsvString); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/bridge/abstraction/MessageTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.bridge.abstraction; 2 | 3 | import guru.springframework.gof.bridge.implementation.EmailMessageSender; 4 | import guru.springframework.gof.bridge.implementation.MessageSender; 5 | import guru.springframework.gof.bridge.implementation.TextMessageSender; 6 | import org.junit.Test; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | 11 | public class MessageTest { 12 | 13 | @Test 14 | public void testSend() throws Exception { 15 | MessageSender textMessageSender=new TextMessageSender(); 16 | Message textMessage=new TextMessage(textMessageSender); 17 | textMessage.send(); 18 | 19 | MessageSender emailMessageSender=new EmailMessageSender(); 20 | Message emailMessage=new TextMessage(emailMessageSender); 21 | emailMessage.send(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/builder/director/ConstructionEngineerTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.builder.director; 2 | 3 | import guru.springframework.gof.builder.builders.HouseBuilder; 4 | import guru.springframework.gof.builder.builders.ConcreteHouseBuilder; 5 | import guru.springframework.gof.builder.builders.PrefabricatedHouseBuilder; 6 | import guru.springframework.gof.builder.product.House; 7 | import org.junit.Test; 8 | 9 | public class ConstructionEngineerTest { 10 | 11 | @Test 12 | public void testConstructHouse() throws Exception { 13 | HouseBuilder concreteHouseBuilder = new ConcreteHouseBuilder(); 14 | ConstructionEngineer engineerA = new ConstructionEngineer(concreteHouseBuilder); 15 | House houseA = engineerA.constructHouse(); 16 | System.out.println("House is: "+houseA); 17 | PrefabricatedHouseBuilder prefabricatedHouseBuilder = new PrefabricatedHouseBuilder(); 18 | ConstructionEngineer engineerB = new ConstructionEngineer(prefabricatedHouseBuilder); 19 | House houseB = engineerB.constructHouse(); 20 | System.out.println("House is: "+houseB); 21 | } 22 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/command/invoker/RemoteControlTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.command.invoker; 2 | 3 | import guru.springframework.gof.command.commandobjects.*; 4 | import guru.springframework.gof.command.receiver.Car; 5 | import guru.springframework.gof.command.receiver.RotatingTop; 6 | import org.junit.Test; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | public class RemoteControlTest { 11 | @Test 12 | public void testRemoteControlButtonPressed() throws Exception { 13 | RemoteControl remoteControl=new RemoteControl(); 14 | System.out.println("-----Testing onButtonPressed on RemoteControl for Car-----"); 15 | Car car=new Car(); 16 | CommandBase carMoveCommand=new CarMoveCommand(car); 17 | remoteControl.onButtonPressed(carMoveCommand); 18 | System.out.println("-----Testing offButtonPressed on RemoteControl for Car-----"); 19 | CommandBase carStopCommand=new CarStopCommand(car); 20 | remoteControl.offButtonPressed(carStopCommand); 21 | System.out.println("-----Testing undoButtonPressed() on RemoteControl for Car-----"); 22 | remoteControl.undoButtonPressed(); 23 | 24 | System.out.println("-----Testing onButtonPressed on RemoteControl for RotatingTop-----"); 25 | RotatingTop top=new RotatingTop(); 26 | CommandBase topRotateCommand=new TopRotateCommand(top); 27 | remoteControl.onButtonPressed(topRotateCommand); 28 | 29 | System.out.println("-----Testing offButtonPressed on RemoteControl for RotatingTop-----"); 30 | CommandBase topStopRotateCommand=new TopStopRotateCommand(top); 31 | remoteControl.offButtonPressed(topStopRotateCommand); 32 | 33 | System.out.println("-----Testing undoButtonPressed on RemoteControl for RotatingTop-----"); 34 | 35 | remoteControl.undoButtonPressed(); 36 | 37 | 38 | } 39 | 40 | 41 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/composite/CatalogComponentTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.composite; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class CatalogComponentTest { 8 | 9 | @Test 10 | public void testPrint() throws Exception { 11 | 12 | 13 | /*Create primary products for main catalog*/ 14 | CatalogComponent mJeanProduct=new Product("M: Jeans 32", 65.00); 15 | CatalogComponent mTShirtProduct=new Product("M: T Shirt 38", 45.00); 16 | 17 | /*Create a composite product catalog and add female products to it*/ 18 | CatalogComponent newCatalog = new ProductCatalog("Female Products"); 19 | CatalogComponent fJeans=new Product("F: Jeans 32", 65.00); 20 | CatalogComponent fTShirts=new Product("F: T Shirt 38", 45.00); 21 | newCatalog.add(fJeans); 22 | newCatalog.add(fTShirts); 23 | 24 | /*Create a composite product catalog and add kid products to it*/ 25 | CatalogComponent kidCatalog = new ProductCatalog("Kids Products"); 26 | CatalogComponent kidShorts=new Product("Return Gift", 23.00); 27 | CatalogComponent kidPlayGears = new Product("Summer Play Gear", 65.00); 28 | kidCatalog.add(kidShorts); 29 | kidCatalog.add(kidPlayGears); 30 | 31 | /*Create primary catalog and add primary products and new catalogs to it*/ 32 | CatalogComponent mainCatalog=new ProductCatalog("Primary Catalog"); 33 | mainCatalog.add(mJeanProduct); 34 | mainCatalog.add(mTShirtProduct); 35 | mainCatalog.add(newCatalog); 36 | mainCatalog.add(kidCatalog); 37 | 38 | /*Print out product/catalog information*/ 39 | mainCatalog.print(); 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/decorator/components/FlowerBouquetTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.decorator.components; 2 | 3 | import guru.springframework.gof.decorator.decorators.Glitter; 4 | import guru.springframework.gof.decorator.decorators.PaperWrapper; 5 | import guru.springframework.gof.decorator.decorators.RibbonBow; 6 | import org.junit.Test; 7 | 8 | 9 | public class FlowerBouquetTest { 10 | @Test 11 | public void testFlowerBouquet() { 12 | /*Rose bouquet with no decoration*/ 13 | FlowerBouquet roseBouquet = new RoseBouquet(); 14 | System.out.println(roseBouquet.getDescription() 15 | + " $ " + roseBouquet.cost()); 16 | 17 | /*Rose bouquet with paper wrapper, ribbon bow, and glitter*/ 18 | FlowerBouquet decoratedRoseBouquet = new RoseBouquet(); 19 | decoratedRoseBouquet=new PaperWrapper(decoratedRoseBouquet); 20 | decoratedRoseBouquet=new RibbonBow(decoratedRoseBouquet); 21 | decoratedRoseBouquet=new Glitter(decoratedRoseBouquet); 22 | System.out.println(decoratedRoseBouquet.getDescription() 23 | + " $ " + decoratedRoseBouquet.cost()); 24 | 25 | /*Orchid bouquet with double paper wrapper and ribbon bow*/ 26 | FlowerBouquet decoratedOrchidBouquet = new OrchidBouquet(); 27 | decoratedOrchidBouquet=new PaperWrapper(decoratedOrchidBouquet); 28 | decoratedOrchidBouquet=new PaperWrapper(decoratedOrchidBouquet); 29 | decoratedOrchidBouquet=new RibbonBow(decoratedOrchidBouquet); 30 | System.out.println(decoratedOrchidBouquet.getDescription() 31 | + " $ " + decoratedOrchidBouquet.cost()); 32 | } 33 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/facade/controller/OrderFulfillmentControllerTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.facade.controller; 2 | 3 | import guru.springframework.gof.facade.servicefacade.OrderServiceFacadeImpl; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | public class OrderFulfillmentControllerTest { 9 | 10 | @Test 11 | public void testOrderProduct() throws Exception { 12 | OrderFulfillmentController controller=new OrderFulfillmentController(); 13 | controller.facade=new OrderServiceFacadeImpl(); 14 | controller.orderProduct(9); 15 | boolean result=controller.orderFulfilled; 16 | assertTrue(result); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/factoryMethod/PizzaFactoryTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.factoryMethod; 2 | 3 | import org.junit.Test; 4 | 5 | public class PizzaFactoryTest { 6 | @Test 7 | public void testMakePizzas(){ 8 | BasePizzaFactory pizzaFactory = new PizzaFactory(); 9 | Pizza cheesePizza = pizzaFactory.createPizza("cheese"); 10 | Pizza veggiePizza = pizzaFactory.createPizza("veggie"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/flyweight/RaceCarClientTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.flyweight; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class RaceCarClientTest { 8 | 9 | @Test 10 | public void testRaceCar() throws Exception { 11 | RaceCarClient raceCars[] = { 12 | new RaceCarClient("Midget"), 13 | new RaceCarClient("Midget"), 14 | new RaceCarClient("Midget"), 15 | new RaceCarClient("Sprint"), 16 | new RaceCarClient("Sprint"), 17 | new RaceCarClient("Sprint") 18 | }; 19 | raceCars[0].moveCar(29, 3112); 20 | raceCars[1].moveCar(39, 2002); 21 | raceCars[2].moveCar(49, 1985); 22 | raceCars[3].moveCar(59, 2543); 23 | raceCars[4].moveCar(69, 2322); 24 | raceCars[5].moveCar(79, 2135); 25 | /*Output and observe the number of instances created*/ 26 | System.out.println("Midget Car Instances: " + FlyweightMidgetCar.num); 27 | System.out.println("Sprint Car Instances: " + FlyweightSprintCar.num); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/interpreter/ExpressionParserTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.interpreter; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | 8 | public class ExpressionParserTest { 9 | 10 | @Test 11 | public void testParse() throws Exception { 12 | String input="2 1 5 + *"; 13 | ExpressionParser expressionParser=new ExpressionParser(); 14 | int result=expressionParser.parse(input); 15 | System.out.println("Final result: "+result); 16 | 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/iterator/PatternAggregateImplTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.iterator; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class PatternAggregateImplTest { 8 | 9 | @Test 10 | public void testPatternIterator() throws Exception { 11 | DesignPattern pattern1 = new DesignPattern("Creational", "Factory Method"); 12 | DesignPattern pattern2 = new DesignPattern("Creational", "Abstract Factory"); 13 | DesignPattern pattern3 = new DesignPattern("Structural", "Adapter"); 14 | DesignPattern pattern4 = new DesignPattern("Structural", "Bridge"); 15 | DesignPattern pattern5 = new DesignPattern("Behavioral", "Chain of Responsibility"); 16 | DesignPattern pattern6 = new DesignPattern("Behavioral", "Iterator"); 17 | 18 | PatternAggregate patternAggregate = new PatternAggregateImpl(); 19 | patternAggregate.addPattern(pattern1); 20 | patternAggregate.addPattern(pattern2); 21 | patternAggregate.addPattern(pattern3); 22 | patternAggregate.addPattern(pattern4); 23 | patternAggregate.addPattern(pattern5); 24 | patternAggregate.addPattern(pattern6); 25 | 26 | System.out.println("-----Pattern list-----"); 27 | printPatterns(patternAggregate); 28 | 29 | patternAggregate.removePattern(pattern1); 30 | patternAggregate.removePattern(pattern2); 31 | 32 | System.out.println("-----Pattern list after removal operation-----"); 33 | printPatterns(patternAggregate); 34 | } 35 | public void printPatterns(PatternAggregate patternAggregate){ 36 | PatternIterator patternIterator= patternAggregate.getPatternIterator(); 37 | while(!patternIterator.isLastPattern()){ 38 | DesignPattern designPattern=patternIterator.nextPattern(); 39 | System.out.println(designPattern.getPatternType() + " : " + designPattern.getPatternName()); 40 | 41 | } 42 | 43 | 44 | } 45 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/mediator/mediator/CommanderImplTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.mediator.mediator; 2 | 3 | import guru.springframework.gof.mediator.colleague.ArmedUnit; 4 | import guru.springframework.gof.mediator.colleague.SoldierUnit; 5 | import guru.springframework.gof.mediator.colleague.TankUnit; 6 | import org.junit.Test; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | 11 | public class CommanderImplTest { 12 | 13 | @Test 14 | public void testMediator() throws Exception { 15 | Commander commander= new CommanderImpl(); 16 | ArmedUnit soldierUnit=new SoldierUnit(commander); 17 | ArmedUnit tankUnit=new TankUnit(commander); 18 | commander.registerArmedUnits(soldierUnit, tankUnit); 19 | commander.startAttack(soldierUnit); 20 | commander.startAttack(tankUnit); 21 | commander.ceaseAttack(soldierUnit); 22 | commander.startAttack(tankUnit); 23 | } 24 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/memento/EmpOriginatorTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.memento; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | 8 | public class EmpOriginatorTest { 9 | 10 | @Test 11 | public void testMemento() throws Exception { 12 | EmpOriginator empOriginator= new EmpOriginator(306,"Mark Ferguson", "131011789610","Sales Manager"); 13 | 14 | EmpMemento empMemento=empOriginator.saveToMemento(); 15 | EmpCaretaker empCaretaker=new EmpCaretaker(); 16 | empCaretaker.addMemento(empMemento); 17 | System.out.println("\n Original EmpOriginator"); 18 | empOriginator.printInfo(); 19 | 20 | 21 | System.out.println("\n EmpOriginator after updating phone number"); 22 | empOriginator.setEmpPhoneNo("131011888886"); 23 | empMemento=empOriginator.saveToMemento(); 24 | empCaretaker.addMemento(empMemento); 25 | empOriginator.printInfo(); 26 | 27 | System.out.println("\n EmpOriginator after updating designation"); 28 | empOriginator.setEmpDesignation("Senior Sales Manager"); 29 | empMemento=empOriginator.saveToMemento(); 30 | empCaretaker.addMemento(empMemento); 31 | empOriginator.printInfo(); 32 | 33 | 34 | System.out.println("\n EmpOriginator after undoing designation update"); 35 | empMemento=empCaretaker.getMemento(); 36 | empOriginator.undoFromMemento(empMemento); 37 | empMemento=empCaretaker.getMemento(); 38 | empOriginator.undoFromMemento(empMemento); 39 | empOriginator.printInfo(); 40 | 41 | 42 | System.out.println("\n Original EmpOriginator after undoing phone number update"); 43 | empMemento=empCaretaker.getMemento(); 44 | empOriginator.undoFromMemento(empMemento); 45 | empOriginator.printInfo(); 46 | 47 | 48 | } 49 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/observer/javaapi/ObservableJavaAPITest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.javaapi; 2 | 3 | 4 | import org.junit.Test; 5 | 6 | import java.math.BigDecimal; 7 | public class ObservableJavaAPITest { 8 | 9 | @Test 10 | public void testObserver() throws Exception { 11 | Product product=new Product("L340 Digital Camera",new BigDecimal(325)); 12 | Bidder bidder1=new Bidder("Shally Ferguson"); 13 | Bidder bidder2=new Bidder("Dwayne Bravo"); 14 | Bidder bidder3=new Bidder("Craig Dawson"); 15 | product.addObserver(bidder1); 16 | product.addObserver(bidder2); 17 | product.addObserver(bidder3); 18 | product.setBidAmount(bidder1, new BigDecimal(350)); 19 | product.deleteObserver(bidder2); 20 | product.setBidAmount(bidder3, new BigDecimal(375)); 21 | } 22 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/observer/observerimpl/ObserverTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.observer.observerimpl; 2 | 3 | import org.junit.Test; 4 | import java.math.BigDecimal; 5 | 6 | public class ObserverTest { 7 | @Test 8 | public void testObserver() throws Exception { 9 | Subject product=new Product("36 inch LED TV",new BigDecimal(350)); 10 | Observer bidder1=new Bidder("Alex Parker"); 11 | Observer bidder2=new Bidder("Henry Smith"); 12 | Observer bidder3=new Bidder("Mary Peterson"); 13 | product.registerObserver(bidder1); 14 | product.registerObserver(bidder2); 15 | product.registerObserver(bidder3); 16 | product.setBidAmount(bidder1, new BigDecimal(375)); 17 | product.removeObserver(bidder2); 18 | product.setBidAmount(bidder3, new BigDecimal(400)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/prototype/DocumentPrototypeManagerTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.prototype; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Created by Admin on 4/21/2015. 9 | */ 10 | public class DocumentPrototypeManagerTest { 11 | 12 | @Test 13 | public void testGetClonedDocument() throws Exception { 14 | PrototypeCapableDocument clonedTAndC = DocumentPrototypeManager.getClonedDocument("tandc"); 15 | clonedTAndC.setVendorName("Mary Parker"); 16 | System.out.println(clonedTAndC); 17 | PrototypeCapableDocument clonedNDA = DocumentPrototypeManager.getClonedDocument("nda"); 18 | clonedNDA.setVendorName("Patrick Smith"); 19 | System.out.println(clonedNDA); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/proxy/ReportGeneratorImplProxyTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.proxy; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class ReportGeneratorImplProxyTest { 8 | 9 | @Test 10 | public void testGenerateReport() throws Exception { 11 | Role accessRole=new Role(); 12 | accessRole.setRole("Manager"); 13 | ReportGenerator proxy=new ReportGeneratorImplProxy(accessRole); 14 | proxy.displayReportTemplate("Pdf",150); 15 | proxy.generateComplexReport("Pdf",150); 16 | proxy.generateSensitiveReport(); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/state/context/CandyVendingMachineTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.state.context; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static org.junit.Assert.*; 7 | 8 | 9 | public class CandyVendingMachineTest { 10 | 11 | @Test 12 | public void testCandyVendingMachine() throws Exception { 13 | System.out.println("-----Test 1: Testing machine by inserting coin and pressing button-----"); 14 | CandyVendingMachine machine=new CandyVendingMachine(3); 15 | System.out.println(machine); 16 | machine.insertCoin(); 17 | System.out.println(machine); 18 | machine.pressButton(); 19 | System.out.println(machine); 20 | 21 | System.out.println("-----Test 2: Testing machine by pressing button without inserting coin-----"); 22 | CandyVendingMachine machine2=new CandyVendingMachine(3); 23 | System.out.println(machine2); 24 | machine2.pressButton(); 25 | System.out.println(machine2); 26 | 27 | System.out.println("-----Test 3: Testing machine running out of candies-----"); 28 | CandyVendingMachine machine3=new CandyVendingMachine(3); 29 | System.out.println(machine3); 30 | machine3.insertCoin(); 31 | machine3.pressButton(); 32 | machine3.insertCoin(); 33 | machine3.pressButton(); 34 | machine3.insertCoin(); 35 | machine3.pressButton(); 36 | machine3.insertCoin(); 37 | machine3.pressButton(); 38 | System.out.println(machine3); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/strategy/context/EncryptorTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.strategy.context; 2 | 3 | import guru.springframework.gof.strategy.strategies.AesEncryptionStrategy; 4 | import guru.springframework.gof.strategy.strategies.BlowfishEncryptionStrategy; 5 | import guru.springframework.gof.strategy.strategies.EncryptionStrategy; 6 | import org.junit.Test; 7 | 8 | import static org.junit.Assert.*; 9 | 10 | 11 | public class EncryptorTest { 12 | 13 | @Test 14 | public void testEncrypt() throws Exception { 15 | EncryptionStrategy aesStrategy=new AesEncryptionStrategy(); 16 | Encryptor aesEncryptor=new Encryptor(aesStrategy); 17 | aesEncryptor.setPlainText("This is plain text"); 18 | aesEncryptor.encrypt(); 19 | 20 | EncryptionStrategy blowfishStrategy=new BlowfishEncryptionStrategy(); 21 | Encryptor blowfishEncryptor=new Encryptor(blowfishStrategy); 22 | blowfishEncryptor.setPlainText("This is plain text"); 23 | blowfishEncryptor.encrypt(); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/templatemethod/PizzaMakerTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.templatemethod; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | 8 | public class PizzaMakerTest { 9 | 10 | @Test 11 | public void testMakePizza() throws Exception { 12 | System.out.println("-----Making Veg Pizza-----"); 13 | PizzaMaker vegPizzaMaker = new VegPizzaMaker(); 14 | vegPizzaMaker.makePizza(); 15 | 16 | System.out.println("-----Making Non Veg Pizza-----"); 17 | PizzaMaker nonVegPizzaMaker = new NonVegPizzaMaker(); 18 | nonVegPizzaMaker.makePizza(); 19 | 20 | System.out.println("-----Making In-House Assorted Pizza-----"); 21 | PizzaMaker inHouseAssortedPizzaMaker = new InHouseAssortedPizzaMaker(); 22 | inHouseAssortedPizzaMaker.makePizza(); 23 | 24 | 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/guru/springframework/gof/visitor/visitors/MailClientVisitorTest.java: -------------------------------------------------------------------------------- 1 | package guru.springframework.gof.visitor.visitors; 2 | 3 | import guru.springframework.gof.visitor.structure.OperaMailClient; 4 | import guru.springframework.gof.visitor.structure.SquirrelMailClient; 5 | import guru.springframework.gof.visitor.structure.ZimbraMailClient; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | import static org.junit.Assert.*; 10 | 11 | public class MailClientVisitorTest { 12 | private MacMailClientVisitor macVisitor; 13 | private LinuxMailClientVisitor linuxVisitor; 14 | private WindowsMailClientVisitor windowsVisitor; 15 | private OperaMailClient operaMailClient; 16 | private SquirrelMailClient squirrelMailClient; 17 | private ZimbraMailClient zimbraMailClient; 18 | 19 | @Before 20 | public void setup(){ 21 | macVisitor=new MacMailClientVisitor(); 22 | linuxVisitor=new LinuxMailClientVisitor(); 23 | windowsVisitor=new WindowsMailClientVisitor(); 24 | operaMailClient = new OperaMailClient(); 25 | squirrelMailClient=new SquirrelMailClient(); 26 | zimbraMailClient=new ZimbraMailClient(); 27 | } 28 | 29 | @Test 30 | public void testOperaMailClient() throws Exception { 31 | System.out.println("-----Testing Opera Mail Client for different environments-----"); 32 | assertTrue(operaMailClient.accept(macVisitor)); 33 | assertTrue(operaMailClient.accept(linuxVisitor)); 34 | assertTrue(operaMailClient.accept(windowsVisitor)); 35 | 36 | } 37 | 38 | @Test 39 | public void testSquirrelMailClient() throws Exception { 40 | System.out.println("\n-----Testing Squirrel Mail Client for different environments-----"); 41 | assertTrue(squirrelMailClient.accept(macVisitor)); 42 | assertTrue(squirrelMailClient.accept(linuxVisitor)); 43 | assertTrue(squirrelMailClient.accept(windowsVisitor)); 44 | 45 | } 46 | 47 | @Test 48 | public void testZimbraMailClient() throws Exception { 49 | System.out.println("\n-----Testing Zimbra Mail Client for different environments-----"); 50 | assertTrue(zimbraMailClient.accept(macVisitor)); 51 | assertTrue(zimbraMailClient.accept(linuxVisitor)); 52 | assertTrue(zimbraMailClient.accept(windowsVisitor)); 53 | 54 | } 55 | } --------------------------------------------------------------------------------