├── .gitignore ├── README.md └── src ├── abstractfactory ├── examples │ ├── kingdom │ │ ├── KingdomTestDrive.java │ │ ├── factories │ │ │ ├── ElfKingdomFactory.java │ │ │ ├── KingdomFactory.java │ │ │ └── MenKingdomFactory.java │ │ └── parts │ │ │ ├── Army.java │ │ │ ├── Castle.java │ │ │ ├── ElfArmy.java │ │ │ ├── ElfCastle.java │ │ │ ├── ElfKing.java │ │ │ ├── King.java │ │ │ ├── MenArmy.java │ │ │ ├── MenCastle.java │ │ │ └── MenKing.java │ └── ufo │ │ ├── ShipsAbstractFactoryTestDrive.java │ │ ├── factories │ │ ├── ShipFactory.java │ │ ├── UFOBossShipFactory.java │ │ └── UFOShipFactory.java │ │ ├── parts │ │ ├── ShipEngine.java │ │ ├── ShipWeapon.java │ │ ├── UFOBossEngine.java │ │ ├── UFOBossGun.java │ │ ├── UFOEngine.java │ │ └── UFOGun.java │ │ └── products │ │ ├── Ship.java │ │ ├── UFOBossShip.java │ │ └── UFOShip.java └── pattern │ ├── AbstractFactory.java │ ├── AbstractProductA.java │ ├── AbstractProductB.java │ ├── ConcreteFactoryOne.java │ ├── ConcreteFactoryTwo.java │ ├── ProductAOne.java │ ├── ProductATwo.java │ ├── ProductBOne.java │ └── ProductBTwo.java ├── adapter ├── examples │ ├── books │ │ ├── AdapterBook.java │ │ ├── Book.java │ │ ├── Client.java │ │ └── SimpleBook.java │ └── users │ │ ├── AbstractConverter.java │ │ ├── Role.java │ │ ├── User.java │ │ ├── UserConverter.java │ │ ├── UserConverterTest.java │ │ └── UserDto.java └── pattern │ ├── Adaptee.java │ ├── Adapter.java │ ├── Client.java │ └── Target.java ├── bridge ├── examples │ └── workshop │ │ ├── Assemble.java │ │ ├── Bike.java │ │ ├── Car.java │ │ ├── Client.java │ │ ├── Produce.java │ │ ├── Vehicle.java │ │ └── Workshop.java └── pattern │ ├── Abstraction.java │ ├── Client.java │ ├── Implementor.java │ ├── ImplementorA.java │ ├── ImplementorB.java │ └── RefinedAbstraction.java ├── builder ├── examples │ ├── fastfood │ │ ├── Cashier.java │ │ ├── ChildrensMealBuilder.java │ │ ├── Costumer.java │ │ ├── FastFoodTest.java │ │ ├── Meal.java │ │ └── MealBuilder.java │ ├── heroes │ │ ├── Armor.java │ │ ├── Hero.java │ │ ├── HeroBuilder.java │ │ ├── HeroTest.java │ │ ├── Profession.java │ │ └── Weapon.java │ ├── pizza │ │ ├── Dough.java │ │ ├── HawaiianPizzaBuilder.java │ │ ├── Ingredients.java │ │ ├── Pizza.java │ │ ├── PizzaBuilder.java │ │ ├── PizzaDirector.java │ │ ├── PizzaTest.java │ │ ├── Sauce.java │ │ └── SpicyPizzaBuilder.java │ └── robots │ │ ├── OldRobotBuilder.java │ │ ├── Robot.java │ │ ├── RobotBuilder.java │ │ ├── RobotBuilderTest.java │ │ └── RobotDirector.java └── pattern │ ├── Builder.java │ ├── Client.java │ ├── ConcreteBuilder.java │ ├── Director.java │ └── Product.java ├── chain └── examples │ └── army │ ├── Client.java │ ├── Officer.java │ ├── Soldier.java │ └── Unit.java ├── command ├── examples │ ├── devices │ │ ├── Client.java │ │ ├── DeviceButton.java │ │ ├── commands │ │ │ ├── Command.java │ │ │ ├── TurnOffAllDevices.java │ │ │ ├── TurnOffTelevision.java │ │ │ ├── TurnOnTelevision.java │ │ │ ├── VolumeDownTelevision.java │ │ │ └── VolumeUpTelevision.java │ │ └── devices │ │ │ ├── ElectronicDevice.java │ │ │ ├── Radio.java │ │ │ └── Television.java │ └── spells │ │ ├── Assistant.java │ │ ├── MagicAct.java │ │ ├── Target.java │ │ ├── Wizard.java │ │ └── commands │ │ ├── Age.java │ │ ├── AgeSpell.java │ │ ├── Command.java │ │ ├── InvisibilitySpell.java │ │ ├── ShrinkSpell.java │ │ ├── Size.java │ │ └── Visibility.java └── pattern │ ├── Client.java │ ├── Command.java │ ├── ConcreteCommand.java │ ├── ConcreteReceiver.java │ ├── Invoker.java │ └── Receiver.java ├── composite ├── examples │ ├── directories │ │ ├── Directory.java │ │ ├── File.java │ │ ├── FileSystem.java │ │ ├── FileSystemTestDrive.java │ │ └── SimpleFile.java │ └── menu │ │ ├── Client.java │ │ ├── MenuComponent.java │ │ ├── MenuComposite.java │ │ ├── MenuItem.java │ │ └── MenuTestDrive.java └── pattern │ ├── Component.java │ ├── Composite.java │ ├── CompositeTest.java │ └── Leaf.java ├── decorator ├── examples │ └── pizzas │ │ ├── Mozzarella.java │ │ ├── Pizza.java │ │ ├── PizzaMaker.java │ │ ├── PlainPizza.java │ │ ├── TomatoSauce.java │ │ └── ToppingDecorator.java └── pattern │ ├── Client.java │ ├── Component.java │ ├── ConcreteComponent.java │ ├── ConcreteDecoratorOne.java │ ├── ConcreteDecoratorTwo.java │ └── Decorator.java ├── facade ├── examples │ ├── bank │ │ ├── AccountNumberCheck.java │ │ ├── BankFacade.java │ │ ├── Client.java │ │ ├── FundsCheck.java │ │ ├── SecurityCodeCheck.java │ │ └── WelcomeMessage.java │ └── computer │ │ ├── CPU.java │ │ ├── ComputerFacade.java │ │ ├── HardDrive.java │ │ ├── Memory.java │ │ └── User.java └── pattern │ ├── Action.java │ ├── Client.java │ ├── ConcreteActionOne.java │ ├── ConcreteActionTwo.java │ └── Facade.java ├── factory ├── examples │ ├── cars │ │ ├── CarsFactoryTestDrive.java │ │ ├── factories │ │ │ ├── CarsFactory.java │ │ │ ├── NissanFactory.java │ │ │ └── ToyotaFactory.java │ │ └── products │ │ │ ├── Camry.java │ │ │ ├── Car.java │ │ │ ├── Corolla.java │ │ │ ├── Tsuru.java │ │ │ └── Versa.java │ └── ships │ │ ├── EnemyShipFactory.java │ │ ├── RocketShip.java │ │ ├── Ship.java │ │ ├── ShipFactory.java │ │ ├── ShipTestDrive.java │ │ └── UFOShip.java └── pattern │ ├── ConcreteFactoryOne.java │ ├── ConcreteFactoryTwo.java │ ├── ConcreteProductOne.java │ ├── ConcreteProductTwo.java │ ├── Factory.java │ ├── FactoryTestDrive.java │ └── Product.java ├── flyweight └── examples │ └── counterstrike │ ├── CounterStrikeTest.java │ ├── CounterTerrorist.java │ ├── Player.java │ ├── PlayerFactory.java │ └── Terrorist.java ├── interpreter └── examples │ └── sql │ ├── Context.java │ ├── Demo.java │ ├── Expression.java │ ├── From.java │ ├── Row.java │ ├── Select.java │ └── Where.java ├── iterator └── examples │ ├── notifications │ ├── Client.java │ ├── Collection.java │ ├── Iterator.java │ ├── Notification.java │ ├── NotificationBar.java │ ├── NotificationCollection.java │ └── NotificationIterator.java │ └── vectors │ ├── Client.java │ ├── Vector.java │ └── VectorIterator.java ├── mediator └── examples │ └── airtrafficcontroller │ ├── Client.java │ ├── Command.java │ ├── ControlTower.java │ ├── Flight.java │ └── Runway.java ├── memento ├── examples │ └── timemachine │ │ ├── Life.java │ │ ├── Memento.java │ │ └── TimeMachineClient.java └── pattern │ ├── Caretaker.java │ ├── Memento.java │ ├── MementoTest.java │ └── Originator.java ├── objectpool └── pattern │ ├── Client.java │ ├── HeavyObject.java │ ├── ObjectPool.java │ └── ObjectPoolTest.java ├── observer ├── examples │ └── auction │ │ ├── AuctionTestDriven.java │ │ ├── Auctioneer.java │ │ └── Bidder.java └── pattern │ ├── ConcreteObserver.java │ ├── ConcreteSubject.java │ ├── Event.java │ ├── Observer.java │ ├── Subject.java │ └── Test.java ├── prototype ├── examples │ └── animals │ │ ├── Animal.java │ │ ├── AnimalCloneFactory.java │ │ ├── AnimalPrototypeTest.java │ │ ├── Cat.java │ │ └── Dog.java └── pattern │ ├── Client.java │ ├── ConcretePrototypeOne.java │ ├── ConcretePrototypeTwo.java │ ├── Prototype.java │ └── PrototypeFactory.java ├── proxy ├── examples │ ├── atm │ │ ├── ATMClient.java │ │ ├── ATMMachine.java │ │ ├── ATMProxy.java │ │ └── GetATMData.java │ └── images │ │ ├── ClientImage.java │ │ ├── Image.java │ │ ├── ProxyImage.java │ │ └── RealImage.java └── pattern │ ├── Client.java │ ├── Proxy.java │ ├── RealSubject.java │ └── Subject.java ├── singleton ├── examples │ └── government │ │ └── Government.java └── pattern │ ├── Singleton.java │ └── Test.java ├── state ├── examples │ └── mobilealerts │ │ ├── AlertStateContext.java │ │ ├── MobileAlertState.java │ │ ├── Ring.java │ │ ├── Silent.java │ │ ├── StateClient.java │ │ └── Vibration.java └── pattern │ ├── Context.java │ ├── State.java │ ├── StateA.java │ └── StateB.java ├── strategy ├── examples │ ├── robot │ │ ├── AgressiveBehavior.java │ │ ├── DefensiveBehavior.java │ │ ├── NormalBehavior.java │ │ ├── Robot.java │ │ ├── RobotBehavior.java │ │ └── RobotTestDrive.java │ └── transportation │ │ ├── CityBus.java │ │ ├── PersonalCar.java │ │ ├── Taxi.java │ │ ├── TransportationMode.java │ │ ├── TransportationModeTestDrive.java │ │ └── Traveler.java └── pattern │ ├── ConcreteStrategyOne.java │ ├── ConcreteStrategyTwo.java │ ├── Context.java │ └── Strategy.java ├── template └── examples │ └── ordermanaging │ ├── Client.java │ ├── NetOrder.java │ ├── OrderProcessTemplate.java │ └── StoreOrder.java └── visitor └── examples ├── airportsecuritycontrol ├── InternationalPassenger.java ├── NationalPassenger.java ├── Passenger.java ├── PoliceOfficer.java └── SecurityControlClient.java └── arithmetic ├── Client.java ├── Constant.java ├── Expression.java ├── Mult.java ├── OpBinary.java ├── Sum.java ├── Variable.java └── VisitorExpression.java /.gitignore: -------------------------------------------------------------------------------- 1 | ########################## 2 | ## Java 3 | ########################## 4 | *.class 5 | .mtj.tmp/ 6 | *.jar 7 | *.war 8 | *.ear 9 | hs_err_pid* 10 | 11 | ########################## 12 | ## Maven 13 | ########################## 14 | target/ 15 | pom.xml.tag 16 | pom.xml.releaseBackup 17 | pom.xml.versionsBackup 18 | pom.xml.next 19 | release.properties 20 | 21 | ########################## 22 | ## IntelliJ 23 | ########################## 24 | *.iml 25 | .idea/ 26 | *.ipr 27 | *.iws 28 | out/ 29 | .idea_modules/ 30 | 31 | ########################## 32 | ## Eclipse 33 | ########################## 34 | .metadata 35 | .classpath 36 | .project 37 | .settings/ 38 | bin/ 39 | tmp/ 40 | *.tmp 41 | *.bak 42 | *.swp 43 | *~.nib 44 | local.properties 45 | .loadpath 46 | 47 | ########################## 48 | ## NetBeans 49 | ########################## 50 | nbproject/private/ 51 | build/ 52 | nbbuild/ 53 | dist/ 54 | nbdist/ 55 | nbactions.xml 56 | nb-configuration.xml 57 | 58 | ########################## 59 | ## OS X 60 | ########################## 61 | .DS_Store 62 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/KingdomTestDrive.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom; 2 | 3 | import abstractfactory.examples.kingdom.factories.ElfKingdomFactory; 4 | import abstractfactory.examples.kingdom.factories.KingdomFactory; 5 | import abstractfactory.examples.kingdom.factories.MenKingdomFactory; 6 | import abstractfactory.examples.kingdom.parts.Army; 7 | import abstractfactory.examples.kingdom.parts.Castle; 8 | import abstractfactory.examples.kingdom.parts.King; 9 | 10 | /** 11 | * Created by luisburgos on 17/07/15. 12 | */ 13 | public class KingdomTestDrive { 14 | 15 | public static void main(String[] args) { 16 | createKingdom(new ElfKingdomFactory()); 17 | createKingdom(new MenKingdomFactory()); 18 | 19 | } 20 | 21 | public static void createKingdom(KingdomFactory factory) { 22 | King king = factory.makeKing(); 23 | Castle castle = factory.makeCastle(); 24 | Army army = factory.makeArmy(); 25 | System.out.println("The kingdom was created: "); 26 | System.out.println(king); 27 | System.out.println(castle); 28 | System.out.println(army); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/factories/ElfKingdomFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.factories; 2 | 3 | import abstractfactory.examples.kingdom.parts.*; 4 | 5 | /** 6 | * Created by luisburgos on 17/07/15. 7 | */ 8 | public class ElfKingdomFactory extends KingdomFactory { 9 | @Override 10 | public Castle makeCastle() { 11 | return new ElfCastle(); 12 | } 13 | 14 | @Override 15 | public King makeKing() { 16 | return new ElfKing(); 17 | } 18 | 19 | @Override 20 | public Army makeArmy() { 21 | return new ElfArmy(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/factories/KingdomFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.factories; 2 | 3 | import abstractfactory.examples.kingdom.parts.Army; 4 | import abstractfactory.examples.kingdom.parts.Castle; 5 | import abstractfactory.examples.kingdom.parts.King; 6 | 7 | /** 8 | * Created by luisburgos on 17/07/15. 9 | */ 10 | public abstract class KingdomFactory { 11 | 12 | public abstract Castle makeCastle(); 13 | public abstract King makeKing(); 14 | public abstract Army makeArmy(); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/factories/MenKingdomFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.factories; 2 | 3 | import abstractfactory.examples.kingdom.parts.*; 4 | 5 | /** 6 | * Created by luisburgos on 17/07/15. 7 | */ 8 | public class MenKingdomFactory extends KingdomFactory { 9 | @Override 10 | public Castle makeCastle() { 11 | return new MenCastle(); 12 | } 13 | 14 | @Override 15 | public King makeKing() { 16 | return new MenKing(); 17 | } 18 | 19 | @Override 20 | public Army makeArmy() { 21 | return new MenArmy(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/Army.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public interface Army { 7 | } 8 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/Castle.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public interface Castle { 7 | } 8 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/ElfArmy.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public class ElfArmy implements Army { 7 | @Override 8 | public String toString() { 9 | return "Elf army!"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/ElfCastle.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public class ElfCastle implements Castle{ 7 | @Override 8 | public String toString() { 9 | return "Elf castle!"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/ElfKing.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public class ElfKing implements King { 7 | @Override 8 | public String toString() { 9 | return "Elf king!"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/King.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public interface King { 7 | } 8 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/MenArmy.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public class MenArmy implements Army{ 7 | @Override 8 | public String toString() { 9 | return "Men army!"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/MenCastle.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public class MenCastle implements Castle { 7 | @Override 8 | public String toString() { 9 | return "Men castle!"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/kingdom/parts/MenKing.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.kingdom.parts; 2 | 3 | /** 4 | * Created by luisburgos on 17/07/15. 5 | */ 6 | public class MenKing implements King { 7 | @Override 8 | public String toString() { 9 | return "Men king!"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/ShipsAbstractFactoryTestDrive.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo; 2 | 3 | import abstractfactory.examples.ufo.factories.UFOBossShipFactory; 4 | import abstractfactory.examples.ufo.products.Ship; 5 | import abstractfactory.examples.ufo.products.UFOBossShip; 6 | import abstractfactory.examples.ufo.products.UFOShip; 7 | 8 | 9 | /** 10 | * Created by luisburgos on 17/07/15. 11 | */ 12 | public class ShipsAbstractFactoryTestDrive { 13 | 14 | public static void main(String[] args) { 15 | 16 | Ship ship; 17 | String typeShip; 18 | 19 | typeShip = "ufo"; 20 | if(typeShip.equalsIgnoreCase("ufo")){ 21 | ship = new UFOShip(); 22 | ship.makeShip(); 23 | System.out.println(ship.toString()); 24 | } 25 | 26 | typeShip = "boss"; 27 | if(typeShip.equalsIgnoreCase("boss")){ 28 | ship = new UFOBossShip(); 29 | ship.makeShip(); 30 | System.out.println(ship.toString()); 31 | } 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/factories/ShipFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.factories; 2 | 3 | import abstractfactory.examples.ufo.parts.ShipEngine; 4 | import abstractfactory.examples.ufo.parts.ShipWeapon; 5 | 6 | /** 7 | * Created by luisburgos on 16/07/15. 8 | */ 9 | public abstract class ShipFactory { 10 | 11 | public abstract ShipWeapon makeShipGun(); 12 | public abstract ShipEngine makeShipEngine(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/factories/UFOBossShipFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.factories; 2 | 3 | import abstractfactory.examples.ufo.parts.ShipEngine; 4 | import abstractfactory.examples.ufo.parts.ShipWeapon; 5 | import abstractfactory.examples.ufo.parts.UFOBossEngine; 6 | import abstractfactory.examples.ufo.parts.UFOBossGun; 7 | 8 | /** 9 | * Created by luisburgos on 16/07/15. 10 | */ 11 | public class UFOBossShipFactory extends ShipFactory { 12 | @Override 13 | public ShipWeapon makeShipGun() { 14 | return new UFOBossGun(); 15 | } 16 | 17 | @Override 18 | public ShipEngine makeShipEngine() { 19 | return new UFOBossEngine(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/factories/UFOShipFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.factories; 2 | 3 | import abstractfactory.examples.ufo.parts.ShipEngine; 4 | import abstractfactory.examples.ufo.parts.ShipWeapon; 5 | import abstractfactory.examples.ufo.parts.UFOEngine; 6 | import abstractfactory.examples.ufo.parts.UFOGun; 7 | 8 | /** 9 | * Created by luisburgos on 16/07/15. 10 | */ 11 | public class UFOShipFactory extends ShipFactory { 12 | @Override 13 | public ShipWeapon makeShipGun() { 14 | return new UFOGun(); 15 | } 16 | 17 | @Override 18 | public ShipEngine makeShipEngine() { 19 | return new UFOEngine(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/parts/ShipEngine.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.parts; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public interface ShipEngine { 7 | public String getShipEngineInformation(); 8 | } 9 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/parts/ShipWeapon.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.parts; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public interface ShipWeapon { 7 | public String getShipWeaponInformation(); 8 | } 9 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/parts/UFOBossEngine.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.parts; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class UFOBossEngine implements ShipEngine { 7 | @Override 8 | public String getShipEngineInformation() { 9 | return "5000 mph"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/parts/UFOBossGun.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.parts; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class UFOBossGun implements ShipWeapon { 7 | @Override 8 | public String getShipWeaponInformation() { 9 | return "50 damage"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/parts/UFOEngine.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.parts; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class UFOEngine implements ShipEngine { 7 | @Override 8 | public String getShipEngineInformation() { 9 | return "1000 mph"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/parts/UFOGun.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.parts; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class UFOGun implements ShipWeapon { 7 | @Override 8 | public String getShipWeaponInformation() { 9 | return "20 damage"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/products/Ship.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.products; 2 | 3 | import abstractfactory.examples.ufo.parts.ShipEngine; 4 | import abstractfactory.examples.ufo.parts.ShipWeapon; 5 | 6 | /** 7 | * Created by luisburgos on 16/07/15. 8 | */ 9 | public abstract class Ship { 10 | 11 | private String name; 12 | private ShipWeapon shipWeapon; 13 | private ShipEngine shipEngine; 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public void setName(String name) { 20 | this.name = name; 21 | } 22 | 23 | public ShipEngine getShipEngine() { 24 | return shipEngine; 25 | } 26 | 27 | public void setShipEngine(ShipEngine shipEngine) { 28 | this.shipEngine = shipEngine; 29 | } 30 | 31 | public ShipWeapon getShipWeapon() { 32 | return shipWeapon; 33 | } 34 | 35 | public void setShipWeapon(ShipWeapon shipWeapon) { 36 | this.shipWeapon = shipWeapon; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "NAME: " + getName() + 42 | " | ENGINE: "+ shipEngine.getShipEngineInformation() + 43 | " | WEAPON: " + shipWeapon.getShipWeaponInformation(); 44 | } 45 | 46 | public abstract void makeShip(); 47 | } 48 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/products/UFOBossShip.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.products; 2 | 3 | import abstractfactory.examples.ufo.factories.ShipFactory; 4 | import abstractfactory.examples.ufo.factories.UFOBossShipFactory; 5 | 6 | /** 7 | * Created by luisburgos on 17/07/15. 8 | */ 9 | public class UFOBossShip extends Ship { 10 | 11 | private ShipFactory shipFactory; 12 | 13 | public UFOBossShip(){ 14 | setName("UFO Boss Ship"); 15 | this.shipFactory = new UFOBossShipFactory(); 16 | } 17 | 18 | @Override 19 | public void makeShip(){ 20 | System.out.println("Making new " + getName()); 21 | setShipEngine(shipFactory.makeShipEngine()); 22 | setShipWeapon(shipFactory.makeShipGun()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/abstractfactory/examples/ufo/products/UFOShip.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.examples.ufo.products; 2 | 3 | import abstractfactory.examples.ufo.factories.ShipFactory; 4 | import abstractfactory.examples.ufo.factories.UFOShipFactory; 5 | 6 | /** 7 | * Created by luisburgos on 17/07/15. 8 | */ 9 | public class UFOShip extends Ship { 10 | 11 | private ShipFactory shipFactory; 12 | 13 | public UFOShip(){ 14 | setName("UFO Ship"); 15 | this.shipFactory = new UFOShipFactory(); 16 | } 17 | 18 | @Override 19 | public void makeShip(){ 20 | System.out.println("Making new " + getName()); 21 | setShipEngine(shipFactory.makeShipEngine()); 22 | setShipWeapon(shipFactory.makeShipGun()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/AbstractFactory.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public abstract class AbstractFactory { 7 | 8 | public abstract AbstractProductA createProductA(); 9 | public abstract AbstractProductB createProductB(); 10 | } 11 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/AbstractProductA.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public abstract class AbstractProductA { 7 | 8 | private String name; 9 | private String description; 10 | 11 | public AbstractProductA() { 12 | } 13 | 14 | public AbstractProductA(String name, String description) { 15 | this.name = name; 16 | this.description = description; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public String getDescription() { 28 | return description; 29 | } 30 | 31 | public void setDescription(String description) { 32 | this.description = description; 33 | } 34 | 35 | public String getInformation(){ 36 | return "Product: " + getName() + " | Description: " + getDescription(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/AbstractProductB.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class AbstractProductB { 7 | 8 | private String name; 9 | private String description; 10 | 11 | public AbstractProductB() { 12 | } 13 | 14 | public AbstractProductB(String name, String description) { 15 | this.name = name; 16 | this.description = description; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public String getDescription() { 28 | return description; 29 | } 30 | 31 | public void setDescription(String description) { 32 | this.description = description; 33 | } 34 | 35 | public String getInformation(){ 36 | return "Product: " + getName() + " | Description: " + getDescription(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/ConcreteFactoryOne.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ConcreteFactoryOne extends AbstractFactory { 7 | @Override 8 | public AbstractProductA createProductA() { 9 | return new ProductAOne(); 10 | } 11 | 12 | @Override 13 | public AbstractProductB createProductB() { 14 | return new ProductBOne(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/ConcreteFactoryTwo.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ConcreteFactoryTwo extends AbstractFactory{ 7 | @Override 8 | public AbstractProductA createProductA() { 9 | return new ProductATwo(); 10 | } 11 | 12 | @Override 13 | public AbstractProductB createProductB() { 14 | return new ProductBTwo(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/ProductAOne.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ProductAOne extends AbstractProductA{ 7 | 8 | public ProductAOne(String name, String description){ 9 | super(name, description); 10 | } 11 | 12 | public ProductAOne(){ 13 | setName("Product A - Part One"); 14 | setDescription("Description of Product A - Part One"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/ProductATwo.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ProductATwo extends AbstractProductA { 7 | 8 | public ProductATwo(String name, String description){ 9 | super(name, description); 10 | } 11 | 12 | public ProductATwo(){ 13 | setName("Product A - Part Two"); 14 | setDescription("Description of Product A - Part Two"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/ProductBOne.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ProductBOne extends AbstractProductB { 7 | 8 | public ProductBOne(String name, String description){ 9 | super(name, description); 10 | } 11 | 12 | public ProductBOne(){ 13 | setName("Product B - Part One"); 14 | setDescription("Description of Product B - Part One"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/abstractfactory/pattern/ProductBTwo.java: -------------------------------------------------------------------------------- 1 | package abstractfactory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ProductBTwo extends AbstractProductB { 7 | 8 | public ProductBTwo(String name, String description){ 9 | super(name, description); 10 | } 11 | 12 | public ProductBTwo(){ 13 | setName("Product B - Part Two"); 14 | setDescription("Description of Product B - Part Two"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/adapter/examples/books/AdapterBook.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.books; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class AdapterBook implements Book{ 7 | 8 | private SimpleBook book; 9 | 10 | public AdapterBook(SimpleBook book) { 11 | this.book = book; 12 | } 13 | 14 | @Override 15 | public String getTitleAndAuthor(){ 16 | return book.getTitle() + " .by " + book.getAuthor(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/adapter/examples/books/Book.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.books; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public interface Book { 7 | public String getTitleAndAuthor(); 8 | } 9 | -------------------------------------------------------------------------------- /src/adapter/examples/books/Client.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.books; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class Client { 7 | public static void main(String[] args) { 8 | Book book; 9 | book = new AdapterBook(new SimpleBook("Refactoring", "Martin Fowler")); 10 | System.out.println(book.getTitleAndAuthor()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/adapter/examples/books/SimpleBook.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.books; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class SimpleBook { 7 | 8 | private String title; 9 | private String author; 10 | 11 | public SimpleBook(String title, String author) { 12 | this.title = title; 13 | this.author = author; 14 | } 15 | 16 | public String getTitle() { 17 | return title; 18 | } 19 | 20 | public String getAuthor() { 21 | return author; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/adapter/examples/users/AbstractConverter.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.users; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | public abstract class AbstractConverter { 7 | 8 | public abstract E fromDto(D dto); 9 | 10 | public abstract D fromEntity(E entity); 11 | 12 | public List fromDto(List dtos){ 13 | if(dtos == null) return null; 14 | return dtos.stream().map(dto -> fromDto(dto)).collect(Collectors.toList()); 15 | } 16 | 17 | public List fromEntity(List entities){ 18 | if(entities == null) return null; 19 | return entities.stream().map(entity -> fromEntity(entity)).collect(Collectors.toList()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/adapter/examples/users/Role.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.users; 2 | 3 | public enum Role { 4 | ADMIN, GUEST; 5 | } 6 | -------------------------------------------------------------------------------- /src/adapter/examples/users/User.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.users; 2 | 3 | import java.util.List; 4 | 5 | public class User { 6 | private Long id; 7 | private String username; 8 | private String password; 9 | private List roles; 10 | private Boolean active; 11 | 12 | public User() { 13 | super(); 14 | } 15 | 16 | public User(Long id, String username, String password, List roles, Boolean active) { 17 | super(); 18 | this.id = id; 19 | this.username = username; 20 | this.password = password; 21 | this.roles = roles; 22 | this.active = active; 23 | } 24 | 25 | public Long getId() { 26 | return id; 27 | } 28 | public void setId(Long id) { 29 | this.id = id; 30 | } 31 | public String getUsername() { 32 | return username; 33 | } 34 | public void setUsername(String username) { 35 | this.username = username; 36 | } 37 | public String getPassword() { 38 | return password; 39 | } 40 | public void setPassword(String password) { 41 | this.password = password; 42 | } 43 | public List getRoles() { 44 | return roles; 45 | } 46 | public void setRoles(List roles) { 47 | this.roles = roles; 48 | } 49 | 50 | @Override 51 | public String toString() { 52 | return "User [id=" + id + ", username=" + username + ", password=" + password + ", roles=" + roles + ", active=" 53 | + active + "]"; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/adapter/examples/users/UserConverter.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.users; 2 | 3 | import java.util.stream.Collectors; 4 | 5 | public class UserConverter extends AbstractConverter{ 6 | 7 | @Override 8 | public User fromDto(UserDto dto) { 9 | User user = new User(); 10 | user.setId(dto.getId()); 11 | user.setUsername(dto.getUsername()); 12 | user.setPassword(dto.getPassword()); 13 | 14 | // Prevent NullPointerException 15 | if(dto.getRoles()!=null) { 16 | user.setRoles(dto.getRoles().stream().map(rol -> Role.valueOf(rol)).collect(Collectors.toList())); 17 | } 18 | return user; 19 | } 20 | 21 | @Override 22 | public UserDto fromEntity(User entity) { 23 | UserDto user = new UserDto(); 24 | user.setId(entity.getId()); 25 | user.setUsername(entity.getUsername()); 26 | user.setPassword(entity.getPassword()); 27 | 28 | // Prevent NullPointerException 29 | if(entity.getRoles()!=null) { 30 | user.setRoles(entity.getRoles().stream().map(rol -> rol.name()).collect(Collectors.toList())); 31 | } 32 | return user; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/adapter/examples/users/UserConverterTest.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.users; 2 | 3 | import java.util.Arrays; 4 | 5 | public class UserConverterTest { 6 | public static void main(String[] args) { 7 | UserDto userDto; 8 | userDto = new UserConverter().fromEntity(new User(1L, "admin", "424df7*9$cae", Arrays.asList(Role.ADMIN), true)); 9 | System.out.println(userDto); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/adapter/examples/users/UserDto.java: -------------------------------------------------------------------------------- 1 | package adapter.examples.users; 2 | 3 | import java.util.List; 4 | 5 | public class UserDto { 6 | private Long id; 7 | private String username; 8 | private String password; 9 | private List roles; 10 | 11 | public Long getId() { 12 | return id; 13 | } 14 | public void setId(Long id) { 15 | this.id = id; 16 | } 17 | public String getUsername() { 18 | return username; 19 | } 20 | public void setUsername(String username) { 21 | this.username = username; 22 | } 23 | public String getPassword() { 24 | return password; 25 | } 26 | public void setPassword(String password) { 27 | this.password = password; 28 | } 29 | public List getRoles() { 30 | return roles; 31 | } 32 | public void setRoles(List roles) { 33 | this.roles = roles; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return "UserDto [id=" + id + ", username=" + username + ", password=" + password + ", roles=" + roles + "]"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/adapter/pattern/Adaptee.java: -------------------------------------------------------------------------------- 1 | package adapter.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class Adaptee { 7 | 8 | private String name; 9 | 10 | public Adaptee(String name){ 11 | this.name = name; 12 | } 13 | 14 | public void specificRequest() { 15 | System.out.println("Called specific request on Adaptee " + name); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/adapter/pattern/Adapter.java: -------------------------------------------------------------------------------- 1 | package adapter.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class Adapter implements Target { 7 | 8 | private Adaptee adaptee; 9 | 10 | public Adapter(Adaptee adaptee){ 11 | this.adaptee = adaptee; 12 | } 13 | 14 | @Override 15 | public void request() { 16 | adaptee.specificRequest(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/adapter/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package adapter.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | Target target; //What client expects 10 | target = new Adapter(new Adaptee("Adaptee One")); 11 | target.request(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/adapter/pattern/Target.java: -------------------------------------------------------------------------------- 1 | package adapter.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public interface Target { 7 | public void request(); 8 | } 9 | -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Assemble.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public class Assemble implements Workshop { 4 | 5 | @Override 6 | public void work() { 7 | System.out.print(" And"); 8 | System.out.println(" Assembled."); 9 | } 10 | } -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Bike.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public class Bike extends Vehicle { 4 | 5 | public Bike(Workshop workShop1, Workshop workShop2) { 6 | super(workShop1, workShop2); 7 | } 8 | 9 | @Override 10 | public void manufacture() { 11 | System.out.print("Bike "); 12 | workShop1.work(); 13 | workShop2.work(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Car.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public class Car extends Vehicle { 4 | 5 | public Car(Workshop workShop1, Workshop workShop2){ 6 | super(workShop1, workShop2); 7 | } 8 | 9 | @Override 10 | public void manufacture() { 11 | System.out.print("Car "); 12 | workShop1.work(); 13 | workShop2.work(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Client.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public class Client { 4 | 5 | public static void main(String[] args) { 6 | Vehicle vehicle1 = new Car(new Produce(), new Assemble()); 7 | vehicle1.manufacture(); 8 | Vehicle vehicle2 = new Bike(new Produce(), new Assemble()); 9 | vehicle2.manufacture(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Produce.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public class Produce implements Workshop { 4 | 5 | @Override 6 | public void work() { 7 | System.out.print("Produced"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Vehicle.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public abstract class Vehicle { 4 | 5 | protected Workshop workShop1; 6 | protected Workshop workShop2; 7 | 8 | protected Vehicle(Workshop workShop1, Workshop workShop2) { 9 | this.workShop1 = workShop1; 10 | this.workShop2 = workShop2; 11 | } 12 | 13 | abstract public void manufacture(); 14 | } 15 | -------------------------------------------------------------------------------- /src/bridge/examples/workshop/Workshop.java: -------------------------------------------------------------------------------- 1 | package bridge.examples.workshop; 2 | 3 | public interface Workshop { 4 | abstract public void work(); 5 | } 6 | -------------------------------------------------------------------------------- /src/bridge/pattern/Abstraction.java: -------------------------------------------------------------------------------- 1 | package bridge.pattern; 2 | 3 | public interface Abstraction { 4 | void operacion(); 5 | } 6 | -------------------------------------------------------------------------------- /src/bridge/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package bridge.pattern; 2 | 3 | public class Client { 4 | 5 | public static void main(String[] args) { 6 | 7 | Abstraction[] abstracciones = new Abstraction[2]; 8 | abstracciones[0] = new RefinedAbstraction(new ImplementorA()); 9 | abstracciones[1] = new RefinedAbstraction(new ImplementorB()); 10 | 11 | for(Abstraction abstraccion:abstracciones) { 12 | abstraccion.operacion(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/bridge/pattern/Implementor.java: -------------------------------------------------------------------------------- 1 | package bridge.pattern; 2 | 3 | public interface Implementor { 4 | void operacion(); 5 | } 6 | -------------------------------------------------------------------------------- /src/bridge/pattern/ImplementorA.java: -------------------------------------------------------------------------------- 1 | package bridge.pattern; 2 | 3 | public class ImplementorA implements Implementor{ 4 | 5 | public void operacion() { 6 | System.out.println("Esta es la implementacion A"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/bridge/pattern/ImplementorB.java: -------------------------------------------------------------------------------- 1 | package bridge.pattern; 2 | 3 | public class ImplementorB implements Implementor{ 4 | 5 | public void operacion() { 6 | System.out.println("Esta es la implementacion B"); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/bridge/pattern/RefinedAbstraction.java: -------------------------------------------------------------------------------- 1 | package bridge.pattern; 2 | 3 | public class RefinedAbstraction implements Abstraction{ 4 | 5 | private Implementor implementador; 6 | 7 | public RefinedAbstraction(Implementor implementador){ 8 | this.implementador = implementador; 9 | } 10 | public void operacion(){ 11 | implementador.operacion(); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/builder/examples/fastfood/Cashier.java: -------------------------------------------------------------------------------- 1 | package builder.examples.fastfood; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Cashier { 7 | 8 | private MealBuilder mealBuilder; 9 | 10 | public Cashier(MealBuilder mealBuilder){ 11 | this.mealBuilder = mealBuilder; 12 | } 13 | 14 | public Meal getMeal(){ 15 | return this.mealBuilder.getMeal(); 16 | } 17 | 18 | public void makeMeal() { 19 | this.mealBuilder.buildBurger(); 20 | this.mealBuilder.buildComplement(); 21 | this.mealBuilder.buildDrink(); 22 | this.mealBuilder.buildToy(); 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/builder/examples/fastfood/ChildrensMealBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.fastfood; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class ChildrensMealBuilder implements MealBuilder{ 7 | 8 | private Meal meal; 9 | 10 | public ChildrensMealBuilder(){ 11 | this.meal = new Meal(); 12 | } 13 | 14 | @Override 15 | public void buildBurger() { 16 | meal.setBurger("Cheese Burger"); 17 | } 18 | 19 | @Override 20 | public void buildDrink() { 21 | meal.setDrink("Orange Juice"); 22 | } 23 | 24 | @Override 25 | public void buildComplement() { 26 | meal.setComplement("Cheese Fingers"); 27 | } 28 | 29 | @Override 30 | public void buildToy() { 31 | meal.setToy("Spongebob Action Figure"); 32 | } 33 | 34 | @Override 35 | public Meal getMeal() { 36 | return meal; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/builder/examples/fastfood/Costumer.java: -------------------------------------------------------------------------------- 1 | package builder.examples.fastfood; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Costumer { 7 | 8 | private Cashier cashier; 9 | 10 | public Costumer(){ 11 | cashier = new Cashier(new ChildrensMealBuilder()); 12 | } 13 | 14 | public Meal getMeal(){ 15 | return cashier.getMeal(); 16 | } 17 | 18 | public void orderMeal(){ 19 | cashier.makeMeal(); 20 | } 21 | 22 | }; -------------------------------------------------------------------------------- /src/builder/examples/fastfood/FastFoodTest.java: -------------------------------------------------------------------------------- 1 | package builder.examples.fastfood; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class FastFoodTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | Costumer costumer = new Costumer(); 11 | costumer.orderMeal(); 12 | 13 | Meal meal = costumer.getMeal(); 14 | 15 | System.out.println("Meal Burger: " + meal.getBurger()); 16 | System.out.println("Meal Drink: " + meal.getDrink()); 17 | System.out.println("Meal Complement: " + meal.getComplement()); 18 | System.out.println("Meal Toy: " + meal.getToy()); 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/builder/examples/fastfood/Meal.java: -------------------------------------------------------------------------------- 1 | package builder.examples.fastfood; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Meal { 7 | 8 | private String burger; 9 | private String drink; 10 | private String complement; 11 | private String toy; 12 | 13 | public String getBurger() { 14 | return burger; 15 | } 16 | 17 | public void setBurger(String burger) { 18 | this.burger = burger; 19 | } 20 | 21 | public String getDrink() { 22 | return drink; 23 | } 24 | 25 | public void setDrink(String drink) { 26 | this.drink = drink; 27 | } 28 | 29 | public String getToy() { 30 | return toy; 31 | } 32 | 33 | public void setToy(String toy) { 34 | this.toy = toy; 35 | } 36 | 37 | public String getComplement() { 38 | return complement; 39 | } 40 | 41 | public void setComplement(String complement) { 42 | this.complement = complement; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/builder/examples/fastfood/MealBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.fastfood; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public interface MealBuilder { 7 | 8 | public void buildBurger(); 9 | public void buildDrink(); 10 | public void buildComplement(); 11 | public void buildToy(); 12 | public Meal getMeal(); 13 | } 14 | -------------------------------------------------------------------------------- /src/builder/examples/heroes/Armor.java: -------------------------------------------------------------------------------- 1 | package builder.examples.heroes; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public enum Armor { 7 | 8 | CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail"); 9 | 10 | private String title; 11 | 12 | Armor(String title) { 13 | this.title = title; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return title; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/builder/examples/heroes/Hero.java: -------------------------------------------------------------------------------- 1 | package builder.examples.heroes; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Hero { 7 | 8 | private String name; 9 | private Profession profession; 10 | private Armor armor; 11 | private Weapon weapon; 12 | 13 | public Hero(){ 14 | 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public void setProfession(Profession profession) { 22 | this.profession = profession; 23 | } 24 | 25 | public void setArmor(Armor armor) { 26 | this.armor = armor; 27 | } 28 | 29 | public void setWeapon(Weapon weapon) { 30 | this.weapon = weapon; 31 | } 32 | 33 | public Profession getProfession() { 34 | return profession; 35 | } 36 | 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public Armor getArmor() { 42 | return armor; 43 | } 44 | 45 | public Weapon getWeapon() { 46 | return weapon; 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | 52 | StringBuilder sb = new StringBuilder(); 53 | sb.append("This is a "); 54 | sb.append(profession); 55 | sb.append(" named "); 56 | sb.append(name); 57 | 58 | if (armor != null) { 59 | sb.append(" wearing "); 60 | sb.append(armor); 61 | } 62 | if (weapon != null) { 63 | sb.append(" and wielding a "); 64 | sb.append(weapon); 65 | } 66 | 67 | sb.append("."); 68 | return sb.toString(); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/builder/examples/heroes/HeroBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.heroes; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class HeroBuilder { 7 | 8 | private Hero hero; 9 | 10 | public HeroBuilder(Profession profession, String name) { 11 | this.hero = new Hero(); 12 | if (profession == null || name == null) { 13 | throw new IllegalArgumentException( 14 | "profession and name can not be null"); 15 | } 16 | hero.setProfession(profession); 17 | hero.setName(name); 18 | } 19 | 20 | public HeroBuilder withArmor(Armor armor) { 21 | hero.setArmor(armor); 22 | return this; 23 | } 24 | 25 | public HeroBuilder withWeapon(Weapon weapon) { 26 | hero.setWeapon(weapon); 27 | return this; 28 | } 29 | 30 | public Hero build() { 31 | return hero; 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/builder/examples/heroes/HeroTest.java: -------------------------------------------------------------------------------- 1 | package builder.examples.heroes; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class HeroTest { 7 | 8 | public static void main(String[] args) { 9 | Hero mage = new HeroBuilder(Profession.MAGE, "Riobard") 10 | .withWeapon(Weapon.DAGGER) 11 | .build(); 12 | System.out.println(mage); 13 | 14 | Hero warrior = new HeroBuilder(Profession.WARRIOR, "Amberjill") 15 | .withArmor(Armor.CHAIN_MAIL) 16 | .withWeapon(Weapon.SWORD).build(); 17 | System.out.println(warrior); 18 | 19 | Hero thief = new HeroBuilder(Profession.THIEF, "Desmond") 20 | .withWeapon(Weapon.BOW).build(); 21 | System.out.println(thief); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/builder/examples/heroes/Profession.java: -------------------------------------------------------------------------------- 1 | package builder.examples.heroes; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public enum Profession { 7 | 8 | WARRIOR, THIEF, MAGE, PRIEST; 9 | 10 | @Override 11 | public String toString() { 12 | return name().toLowerCase(); 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/builder/examples/heroes/Weapon.java: -------------------------------------------------------------------------------- 1 | package builder.examples.heroes; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public enum Weapon { 7 | 8 | DAGGER, SWORD, AXE, WARHAMMER, BOW; 9 | 10 | @Override 11 | public String toString() { 12 | return name().toLowerCase(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/Dough.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public enum Dough { 7 | 8 | CROSS, PANBAKED; 9 | 10 | @Override 11 | public String toString() { 12 | return name().toLowerCase(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/HawaiianPizzaBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class HawaiianPizzaBuilder extends PizzaBuilder{ 7 | 8 | public HawaiianPizzaBuilder(){ 9 | this.createNewPizzaProduct(); 10 | this.setDough(Dough.CROSS); 11 | this.setSauce(Sauce.MILD); 12 | } 13 | 14 | @Override 15 | public PizzaBuilder setTopping(Ingredients topping) { 16 | pizza.setTopping(topping); 17 | return this; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/Ingredients.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public enum Ingredients { 7 | 8 | PEPPERONI, SALAMI, HAM, MUSHROOMS, PINEAPPLE; 9 | 10 | @Override 11 | public String toString() { 12 | return name().toLowerCase(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/Pizza.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Pizza { 7 | 8 | private Dough dough; 9 | private Sauce sauce; 10 | private Ingredients topping; 11 | 12 | public Pizza(){} 13 | 14 | public Dough getDough() { 15 | return dough; 16 | } 17 | 18 | public void setDough(Dough dough) { 19 | this.dough = dough; 20 | } 21 | 22 | public Sauce getSauce() { 23 | return sauce; 24 | } 25 | 26 | public void setSauce(Sauce sauce) { 27 | this.sauce = sauce; 28 | } 29 | 30 | public Ingredients getTopping() { 31 | return topping; 32 | } 33 | 34 | public void setTopping(Ingredients topping) { 35 | this.topping = topping; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | StringBuilder output = new StringBuilder(); 41 | 42 | output.append("This is a Pizza with " + getDough() + " dough, " + getSauce() + " ,sauce"); 43 | 44 | if(topping != null){ 45 | output.append(" and " + topping); 46 | } 47 | 48 | output.append("."); 49 | 50 | return output.toString(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/PizzaBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | import builder.examples.heroes.Armor; 4 | 5 | /** 6 | * Created by luisburgos on 22/07/15. 7 | */ 8 | public abstract class PizzaBuilder { 9 | 10 | protected Pizza pizza; 11 | 12 | public Pizza getPizza() { return pizza; } 13 | public void createNewPizzaProduct() { pizza = new Pizza(); } 14 | 15 | public PizzaBuilder setSauce(Sauce sauce) { 16 | pizza.setSauce(sauce); 17 | return this; 18 | } 19 | 20 | public PizzaBuilder setDough(Dough dough) { 21 | pizza.setDough(dough); 22 | return this; 23 | } 24 | 25 | public abstract PizzaBuilder setTopping(Ingredients topping); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/PizzaDirector.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class PizzaDirector { 7 | 8 | private PizzaBuilder pizzaBuilder; 9 | 10 | public PizzaDirector(PizzaBuilder pizzaBuilder) { 11 | this.pizzaBuilder = pizzaBuilder; 12 | } 13 | 14 | public Pizza getPizza(){ 15 | return pizzaBuilder.getPizza(); 16 | } 17 | 18 | public PizzaDirector makePizza(Ingredients topping){ 19 | pizzaBuilder.createNewPizzaProduct(); 20 | pizzaBuilder.setTopping(topping); 21 | return this; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/PizzaTest.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class PizzaTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | Pizza pizza = new PizzaDirector(new SpicyPizzaBuilder()) 11 | .makePizza(Ingredients.HAM) 12 | .getPizza(); 13 | 14 | System.out.println(pizza.toString()); 15 | 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/Sauce.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public enum Sauce { 7 | 8 | HOT, MILD; 9 | 10 | @Override 11 | public String toString() { 12 | return name().toLowerCase(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/builder/examples/pizza/SpicyPizzaBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.pizza; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class SpicyPizzaBuilder extends PizzaBuilder { 7 | 8 | public SpicyPizzaBuilder(){ 9 | this.createNewPizzaProduct(); 10 | this.setDough(Dough.PANBAKED); 11 | this.setSauce(Sauce.HOT); 12 | } 13 | 14 | @Override 15 | public PizzaBuilder setTopping(Ingredients topping) { 16 | pizza.setTopping(topping); 17 | return this; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/builder/examples/robots/OldRobotBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.robots; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class OldRobotBuilder implements RobotBuilder { 7 | 8 | private Robot robot; 9 | 10 | public OldRobotBuilder () { 11 | this.robot = new Robot(); 12 | } 13 | 14 | @Override 15 | public void buildRobotHead() { 16 | robot.setRobotHead("Old Head"); 17 | } 18 | 19 | @Override 20 | public void buildRobotTorso() { 21 | robot.setRobotTorso("Old Torso"); 22 | } 23 | 24 | @Override 25 | public void buildRobotArms() { 26 | robot.setRobotArms("Old Arms"); 27 | } 28 | 29 | @Override 30 | public void buildRobotLegs() { 31 | robot.setRobotLegs("Old Legs"); 32 | } 33 | 34 | @Override 35 | public Robot getRobot() { 36 | return robot; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/builder/examples/robots/Robot.java: -------------------------------------------------------------------------------- 1 | package builder.examples.robots; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Robot { 7 | 8 | private String robotHead; 9 | private String robotTorso; 10 | private String robotArms; 11 | private String robotLegs; 12 | 13 | public String getRobotHead() { 14 | return robotHead; 15 | } 16 | 17 | public void setRobotHead(String robotHead) { 18 | this.robotHead = robotHead; 19 | } 20 | 21 | public String getRobotTorso() { 22 | return robotTorso; 23 | } 24 | 25 | public void setRobotTorso(String robotTorso) { 26 | this.robotTorso = robotTorso; 27 | } 28 | 29 | public String getRobotArms() { 30 | return robotArms; 31 | } 32 | 33 | public void setRobotArms(String robotArms) { 34 | this.robotArms = robotArms; 35 | } 36 | 37 | public String getRobotLegs() { 38 | return robotLegs; 39 | } 40 | 41 | public void setRobotLegs(String robotLegs) { 42 | this.robotLegs = robotLegs; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/builder/examples/robots/RobotBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.examples.robots; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public interface RobotBuilder { 7 | 8 | public void buildRobotHead(); 9 | public void buildRobotTorso(); 10 | public void buildRobotArms(); 11 | public void buildRobotLegs(); 12 | public Robot getRobot(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/builder/examples/robots/RobotBuilderTest.java: -------------------------------------------------------------------------------- 1 | package builder.examples.robots; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class RobotBuilderTest { 7 | 8 | public static void main(String[] args){ 9 | 10 | RobotBuilder oldStyleRobot = new OldRobotBuilder(); 11 | RobotDirector robotEngineer = new RobotDirector(oldStyleRobot); 12 | robotEngineer.makeRobot(); 13 | 14 | 15 | Robot firstRobot = robotEngineer.getRobot(); 16 | 17 | System.out.println("Robot Built"); 18 | System.out.println("Robot Head Type: " + firstRobot.getRobotHead()); 19 | System.out.println("Robot Torso Type: " + firstRobot.getRobotTorso()); 20 | System.out.println("Robot Arm Type: " + firstRobot.getRobotArms()); 21 | System.out.println("Robot Leg Type: " + firstRobot.getRobotLegs()); 22 | 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/builder/examples/robots/RobotDirector.java: -------------------------------------------------------------------------------- 1 | package builder.examples.robots; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class RobotDirector { 7 | 8 | private RobotBuilder robotBuilder; 9 | 10 | public RobotDirector(RobotBuilder robotBuilder){ 11 | this.robotBuilder = robotBuilder; 12 | } 13 | 14 | public Robot getRobot(){ 15 | return this.robotBuilder.getRobot(); 16 | } 17 | 18 | public void makeRobot() { 19 | this.robotBuilder.buildRobotHead(); 20 | this.robotBuilder.buildRobotTorso(); 21 | this.robotBuilder.buildRobotArms(); 22 | this.robotBuilder.buildRobotLegs(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/builder/pattern/Builder.java: -------------------------------------------------------------------------------- 1 | package builder.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public interface Builder { 7 | public void buildPartOne(); 8 | public void buildPartTwo(); 9 | public void buildPartThree(); 10 | public Product getProduct(); 11 | } 12 | -------------------------------------------------------------------------------- /src/builder/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package builder.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | 10 | Director director = new Director(new ConcreteBuilder()); 11 | 12 | director.makeProduct(); 13 | 14 | Product product = director.getProduct(); 15 | 16 | System.out.println("Product part: " + product.getPartOne()); 17 | System.out.println("Product part: " + product.getPartTwo()); 18 | System.out.println("Product part: " + product.getPartThree()); 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/builder/pattern/ConcreteBuilder.java: -------------------------------------------------------------------------------- 1 | package builder.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class ConcreteBuilder implements Builder{ 7 | 8 | private Product product; 9 | 10 | public ConcreteBuilder() { 11 | this.product = new Product(); 12 | } 13 | 14 | @Override 15 | public void buildPartOne() { 16 | product.setPartOne("Part One"); 17 | } 18 | 19 | @Override 20 | public void buildPartTwo() { 21 | product.setPartTwo("Part Two"); 22 | } 23 | 24 | @Override 25 | public void buildPartThree() { 26 | product.setPartThree("Part Three"); 27 | } 28 | 29 | @Override 30 | public Product getProduct() { 31 | return product; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/builder/pattern/Director.java: -------------------------------------------------------------------------------- 1 | package builder.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Director { 7 | 8 | private Builder builder; 9 | 10 | public Director(Builder builder){ 11 | this.builder = builder; 12 | } 13 | 14 | public void makeProduct(){ 15 | builder.buildPartOne(); 16 | builder.buildPartTwo(); 17 | builder.buildPartThree(); 18 | } 19 | 20 | public Product getProduct(){ 21 | return builder.getProduct(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/builder/pattern/Product.java: -------------------------------------------------------------------------------- 1 | package builder.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 22/07/15. 5 | */ 6 | public class Product { 7 | 8 | private String partOne; 9 | private String partTwo; 10 | private String partThree; 11 | 12 | public String getPartOne() { 13 | return partOne; 14 | } 15 | 16 | public void setPartOne(String partOne) { 17 | this.partOne = partOne; 18 | } 19 | 20 | public String getPartTwo() { 21 | return partTwo; 22 | } 23 | 24 | public void setPartTwo(String partTwo) { 25 | this.partTwo = partTwo; 26 | } 27 | 28 | public String getPartThree() { 29 | return partThree; 30 | } 31 | 32 | public void setPartThree(String partThree) { 33 | this.partThree = partThree; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/chain/examples/army/Client.java: -------------------------------------------------------------------------------- 1 | package chain.examples.army; 2 | 3 | public class Client { 4 | 5 | public static void main(String argv[]) { 6 | Unit smith = new Officer("Smith", "Descanse"); 7 | Unit truman = new Officer("Truman", "Tomar posición enemiga"); 8 | Unit ryan = new Soldier("Ryan"); 9 | Unit rambo = new Soldier("Rambo"); 10 | 11 | System.out.println(rambo.order()); // rambo -> ? 12 | 13 | rambo.setCommand(truman); 14 | System.out.println(rambo.order()); // rambo -> truman 15 | 16 | ryan.setCommand(rambo); 17 | System.out.println(ryan.order()); // ryan -> rambo -> truman 18 | 19 | truman.setCommand(smith); 20 | System.out.println(ryan.order()); // ryan -> rambo -> truman -> smith 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/chain/examples/army/Officer.java: -------------------------------------------------------------------------------- 1 | 2 | package chain.examples.army; 3 | 4 | public class Officer extends Unit { 5 | 6 | private String _order; 7 | 8 | public Officer(String name, String order) { 9 | super(name); 10 | _order = order; 11 | } 12 | 13 | public String order() { 14 | String result=null; 15 | 16 | if(super.order()!=null && !super.order().equals(UNKNOWN_ORDER)) { 17 | result = super.order(); 18 | 19 | }else if (_order != null) { 20 | result = _order; 21 | } 22 | 23 | return result; 24 | 25 | } 26 | 27 | public String toString() { 28 | return ("Oficial " + super.toString()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/chain/examples/army/Soldier.java: -------------------------------------------------------------------------------- 1 | package chain.examples.army; 2 | 3 | public class Soldier extends Unit { 4 | 5 | public Soldier(String name) { 6 | super(name); 7 | } 8 | 9 | public String toString() { 10 | return ("Soldado " + super.toString()); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/chain/examples/army/Unit.java: -------------------------------------------------------------------------------- 1 | package chain.examples.army; 2 | 3 | public abstract class Unit { 4 | 5 | static final String UNKNOWN_ORDER = "(sin orden)"; 6 | 7 | private Unit _command; 8 | private String _name; 9 | 10 | public Unit(String name) { 11 | _command = null; 12 | _name = name; 13 | } 14 | 15 | public String toString() { 16 | return _name; 17 | } 18 | 19 | public void setCommand(Unit command) { 20 | _command = command; 21 | } 22 | 23 | public String order() { 24 | return (_command != null ? _command.order() : UNKNOWN_ORDER); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/command/examples/devices/Client.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices; 2 | 3 | import command.examples.devices.commands.TurnOffAllDevices; 4 | import command.examples.devices.commands.TurnOffTelevision; 5 | import command.examples.devices.commands.TurnOnTelevision; 6 | import command.examples.devices.commands.VolumeUpTelevision; 7 | import command.examples.devices.devices.ElectronicDevice; 8 | import command.examples.devices.devices.Radio; 9 | import command.examples.devices.devices.Television; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * Created by luisburgos on 13/08/15. 16 | */ 17 | public class Client { 18 | 19 | public static void main(String[] args){ 20 | 21 | ElectronicDevice televisionOne = new Television("SAMSUMG"); 22 | 23 | TurnOnTelevision onCommand = new TurnOnTelevision(televisionOne); 24 | 25 | DeviceButton onPressed; 26 | onPressed = new DeviceButton(onCommand); 27 | onPressed.press(); 28 | 29 | 30 | TurnOffTelevision offCommand = new TurnOffTelevision(televisionOne); 31 | onPressed = new DeviceButton(offCommand); 32 | onPressed.press(); 33 | 34 | VolumeUpTelevision volUpCommand = new VolumeUpTelevision(televisionOne); 35 | onPressed = new DeviceButton(volUpCommand); 36 | onPressed.press(); 37 | onPressed.press(); 38 | onPressed.press(); 39 | 40 | Television televisionTwo = new Television("SONY"); 41 | Radio radioOne = new Radio("PIONEER"); 42 | 43 | List allDevices = new ArrayList<>(); 44 | 45 | allDevices.add(televisionTwo); 46 | allDevices.add(radioOne); 47 | 48 | TurnOffAllDevices turnOffDevices = new TurnOffAllDevices(allDevices); 49 | 50 | DeviceButton turnThemOff = new DeviceButton(turnOffDevices); 51 | 52 | turnThemOff.press(); 53 | turnThemOff.pressUndo(); 54 | 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/command/examples/devices/DeviceButton.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices; 2 | 3 | import command.examples.devices.commands.Command; 4 | 5 | /** 6 | * The INVOKER 7 | * Created by luisburgos on 13/08/15. 8 | */ 9 | public class DeviceButton { 10 | 11 | private Command command; 12 | 13 | public DeviceButton(Command command){ 14 | this.command = command; 15 | } 16 | 17 | public void press(){ 18 | command.execute(); 19 | } 20 | 21 | public void pressUndo(){ 22 | command.undo(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/command/examples/devices/commands/Command.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.commands; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public interface Command { 7 | public void execute(); 8 | public void undo(); 9 | } 10 | -------------------------------------------------------------------------------- /src/command/examples/devices/commands/TurnOffAllDevices.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.commands; 2 | 3 | import command.examples.devices.devices.ElectronicDevice; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by luisburgos on 13/08/15. 9 | */ 10 | public class TurnOffAllDevices implements Command { 11 | 12 | List allDevices; 13 | 14 | public TurnOffAllDevices(List newDevices) { 15 | allDevices = newDevices; 16 | } 17 | 18 | public void execute() { 19 | for (ElectronicDevice device : allDevices) { 20 | device.off(); 21 | } 22 | } 23 | 24 | public void undo() { 25 | for (ElectronicDevice device : allDevices) { 26 | device.on(); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/command/examples/devices/commands/TurnOffTelevision.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.commands; 2 | 3 | import command.examples.devices.devices.ElectronicDevice; 4 | 5 | /** 6 | * Created by luisburgos on 13/08/15. 7 | */ 8 | public class TurnOffTelevision implements Command { 9 | 10 | private ElectronicDevice device; 11 | 12 | public TurnOffTelevision(ElectronicDevice device){ 13 | this.device = device; 14 | } 15 | 16 | @Override 17 | public void execute() { 18 | device.off(); 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | device.on(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/command/examples/devices/commands/TurnOnTelevision.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.commands; 2 | 3 | import command.examples.devices.devices.ElectronicDevice; 4 | 5 | /** 6 | * Created by luisburgos on 13/08/15. 7 | */ 8 | public class TurnOnTelevision implements Command { 9 | 10 | private ElectronicDevice device; 11 | 12 | public TurnOnTelevision(ElectronicDevice device){ 13 | this.device = device; 14 | } 15 | 16 | @Override 17 | public void execute() { 18 | device.on(); 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | device.off(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/command/examples/devices/commands/VolumeDownTelevision.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.commands; 2 | 3 | import command.examples.devices.devices.ElectronicDevice; 4 | 5 | /** 6 | * Created by luisburgos on 13/08/15. 7 | */ 8 | public class VolumeDownTelevision implements Command { 9 | 10 | private ElectronicDevice device; 11 | 12 | public VolumeDownTelevision(ElectronicDevice device){ 13 | this.device = device; 14 | } 15 | 16 | @Override 17 | public void execute() { 18 | device.volumenDown(); 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | device.volumeUp(); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/command/examples/devices/commands/VolumeUpTelevision.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.commands; 2 | 3 | import command.examples.devices.devices.ElectronicDevice; 4 | 5 | /** 6 | * Created by luisburgos on 13/08/15. 7 | */ 8 | public class VolumeUpTelevision implements Command { 9 | 10 | private ElectronicDevice device; 11 | 12 | public VolumeUpTelevision(ElectronicDevice device){ 13 | this.device = device; 14 | } 15 | 16 | @Override 17 | public void execute() { 18 | device.volumeUp(); 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | device.volumenDown(); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/command/examples/devices/devices/ElectronicDevice.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.devices; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public interface ElectronicDevice { 7 | public void on(); 8 | public void off(); 9 | public void volumeUp(); 10 | public void volumenDown(); 11 | } 12 | -------------------------------------------------------------------------------- /src/command/examples/devices/devices/Radio.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.devices; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public class Radio implements ElectronicDevice { 7 | 8 | private int volume = 0; 9 | private String name; 10 | 11 | public Radio(String name) { 12 | this.name = name; 13 | } 14 | 15 | @Override 16 | public void on() { 17 | System.out.println(name + "RADIO is on"); 18 | } 19 | 20 | @Override 21 | public void off() { 22 | System.out.println(name + "RADIO is off"); 23 | } 24 | 25 | @Override 26 | public void volumeUp() { 27 | volume++; 28 | System.out.println(name + "RADIO Volume at: " + volume); 29 | } 30 | 31 | @Override 32 | public void volumenDown() { 33 | volume--; 34 | System.out.println(name + "RADIO Volume at: " + volume); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/command/examples/devices/devices/Television.java: -------------------------------------------------------------------------------- 1 | package command.examples.devices.devices; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public class Television implements ElectronicDevice { 7 | 8 | private int volume = 0; 9 | private String name; 10 | 11 | public Television(String name) { 12 | this.name = name; 13 | } 14 | 15 | @Override 16 | public void on() { 17 | System.out.println(name + "TV is on"); 18 | } 19 | 20 | @Override 21 | public void off() { 22 | System.out.println(name + "TV is off"); 23 | } 24 | 25 | @Override 26 | public void volumeUp() { 27 | volume++; 28 | System.out.println(name + "TV Volume at: " + volume); 29 | } 30 | 31 | @Override 32 | public void volumenDown() { 33 | volume--; 34 | System.out.println(name + "TV Volume at: " + volume); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/command/examples/spells/Assistant.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells; 2 | 3 | import command.examples.spells.commands.Age; 4 | import command.examples.spells.commands.Size; 5 | import command.examples.spells.commands.Visibility; 6 | 7 | /** 8 | * The RECEIVER 9 | * Created by luisburgos on 14/08/15. 10 | */ 11 | public class Assistant extends Target { 12 | 13 | public Assistant() { 14 | setSize(Size.NORMAL); 15 | setVisibility(Visibility.VISIBLE); 16 | setAge(Age.ADULT); 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return "Assistant"; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/command/examples/spells/MagicAct.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells; 2 | 3 | import command.examples.spells.commands.AgeSpell; 4 | import command.examples.spells.commands.InvisibilitySpell; 5 | import command.examples.spells.commands.ShrinkSpell; 6 | 7 | /** 8 | * Main Magic Act. 9 | * Created by luisburgos on 14/08/15. 10 | */ 11 | public class MagicAct { 12 | 13 | public static void main(String[] args) { 14 | Wizard wizard = new Wizard(); 15 | Assistant assistant = new Assistant(); 16 | 17 | assistant.printStatus(); 18 | 19 | wizard.castSpell(new ShrinkSpell(), assistant); 20 | assistant.printStatus(); 21 | 22 | wizard.castSpell(new InvisibilitySpell(), assistant); 23 | assistant.printStatus(); 24 | 25 | wizard.undoLastSpell(); 26 | assistant.printStatus(); 27 | 28 | wizard.undoLastSpell(); 29 | assistant.printStatus(); 30 | 31 | wizard.redoLastSpell(); 32 | assistant.printStatus(); 33 | 34 | wizard.redoLastSpell(); 35 | assistant.printStatus(); 36 | 37 | ///Add a new spell 38 | wizard.castSpell(new AgeSpell(), assistant); 39 | assistant.printStatus(); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/command/examples/spells/Target.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells; 2 | 3 | import command.examples.spells.commands.Age; 4 | import command.examples.spells.commands.Size; 5 | import command.examples.spells.commands.Visibility; 6 | 7 | /** 8 | * Created by luisburgos on 14/08/15. 9 | */ 10 | public abstract class Target { 11 | 12 | private Size size; 13 | private Visibility visibility; 14 | private Age age; 15 | 16 | public Size getSize() { 17 | return size; 18 | } 19 | 20 | public void setSize(Size size) { 21 | this.size = size; 22 | } 23 | 24 | public Visibility getVisibility() { 25 | return visibility; 26 | } 27 | 28 | public void setVisibility(Visibility visibility) { 29 | this.visibility = visibility; 30 | } 31 | 32 | public Age getAge() { 33 | return age; 34 | } 35 | 36 | public void setAge(Age age) { 37 | this.age = age; 38 | } 39 | 40 | @Override 41 | public abstract String toString(); 42 | 43 | public void printStatus() { 44 | System.out.println(String.format("%s, Size: %s | Visibility: %s | Age: %s \n", this, 45 | getSize(), getVisibility(), getAge())); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/command/examples/spells/Wizard.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells; 2 | 3 | import command.examples.spells.commands.Command; 4 | 5 | import java.util.Deque; 6 | import java.util.LinkedList; 7 | 8 | /** 9 | * The INVOKER 10 | * Created by luisburgos on 14/08/15. 11 | */ 12 | public class Wizard { 13 | 14 | private Deque undoStack = new LinkedList<>(); 15 | private Deque redoStack = new LinkedList<>(); 16 | 17 | public Wizard() { 18 | } 19 | 20 | public void castSpell(Command command, Target target) { 21 | System.out.println(this + " casts " + command + " at " + target); 22 | command.execute(target); 23 | undoStack.offerLast(command); 24 | } 25 | 26 | public void undoLastSpell() { 27 | if (!undoStack.isEmpty()) { 28 | Command previousSpell = undoStack.pollLast(); 29 | redoStack.offerLast(previousSpell); 30 | System.out.println(this + " undoes " + previousSpell); 31 | previousSpell.undo(); 32 | } 33 | } 34 | 35 | public void redoLastSpell() { 36 | if (!redoStack.isEmpty()) { 37 | Command previousSpell = redoStack.pollLast(); 38 | undoStack.offerLast(previousSpell); 39 | System.out.println(this + " redoes " + previousSpell); 40 | previousSpell.redo(); 41 | } 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "Wizard"; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/command/examples/spells/commands/Age.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | /** 4 | * Created by luisburgos on 14/08/15. 5 | */ 6 | public enum Age { 7 | CHILD("small"), ADULT("adult"), ELDER("elder"), UNDEFINED(""); 8 | 9 | private String title; 10 | 11 | Age(String title) { 12 | this.title = title; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return title; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/command/examples/spells/commands/AgeSpell.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | import command.examples.spells.Target; 4 | 5 | /** 6 | * Created by luisburgos on 14/08/15. 7 | */ 8 | public class AgeSpell extends Command { 9 | 10 | private Age previousAge; 11 | private Target target; 12 | 13 | 14 | @Override 15 | public void execute(Target target) { 16 | previousAge = target.getAge(); 17 | target.setAge(Age.ELDER); 18 | this.target = target; 19 | } 20 | 21 | @Override 22 | public void undo() { 23 | if (previousAge != null && target != null) { 24 | Age temp = target.getAge(); 25 | target.setAge(previousAge); 26 | previousAge = temp; 27 | } 28 | } 29 | 30 | @Override 31 | public void redo() { 32 | undo(); 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return "Age Spell"; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/command/examples/spells/commands/Command.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | import command.examples.spells.Target; 4 | 5 | /** 6 | * Created by luisburgos on 14/08/15. 7 | */ 8 | public abstract class Command { 9 | 10 | public abstract void execute(Target target); 11 | public abstract void undo(); 12 | public abstract void redo(); 13 | 14 | @Override 15 | public abstract String toString(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/command/examples/spells/commands/InvisibilitySpell.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | import command.examples.spells.Target; 4 | 5 | /** 6 | * Created by luisburgos on 14/08/15. 7 | */ 8 | public class InvisibilitySpell extends Command { 9 | 10 | private Target target; 11 | 12 | @Override 13 | public void execute(Target target) { 14 | target.setVisibility(Visibility.INVISIBLE); 15 | this.target = target; 16 | } 17 | 18 | @Override 19 | public void undo() { 20 | if (target != null) { 21 | target.setVisibility(Visibility.VISIBLE); 22 | } 23 | } 24 | 25 | @Override 26 | public void redo() { 27 | if (target != null) { 28 | target.setVisibility(Visibility.INVISIBLE); 29 | } 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "Invisibility spell"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/command/examples/spells/commands/ShrinkSpell.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | import command.examples.spells.Target; 4 | 5 | /** 6 | * Created by luisburgos on 14/08/15. 7 | */ 8 | public class ShrinkSpell extends Command { 9 | 10 | private Size oldSize; 11 | private Target target; 12 | 13 | @Override 14 | public void execute(Target target) { 15 | oldSize = target.getSize(); 16 | target.setSize(Size.SMALL); 17 | this.target = target; 18 | } 19 | 20 | @Override 21 | public void undo() { 22 | if (oldSize != null && target != null) { 23 | Size temp = target.getSize(); 24 | target.setSize(oldSize); 25 | oldSize = temp; 26 | } 27 | } 28 | 29 | @Override 30 | public void redo() { 31 | undo(); 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "Shrink spell"; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/command/examples/spells/commands/Size.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | /** 4 | * Created by luisburgos on 14/08/15. 5 | */ 6 | public enum Size { 7 | 8 | SMALL("small"), NORMAL("normal"), LARGE("large"), UNDEFINED(""); 9 | 10 | private String title; 11 | 12 | Size(String title) { 13 | this.title = title; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return title; 19 | } 20 | } -------------------------------------------------------------------------------- /src/command/examples/spells/commands/Visibility.java: -------------------------------------------------------------------------------- 1 | package command.examples.spells.commands; 2 | 3 | /** 4 | * Created by luisburgos on 14/08/15. 5 | */ 6 | public enum Visibility { 7 | 8 | VISIBLE("visible"), INVISIBLE("invisible"), UNDEFINED(""); 9 | 10 | private String title; 11 | 12 | Visibility(String title) { 13 | this.title = title; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return title; 19 | } 20 | } -------------------------------------------------------------------------------- /src/command/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package command.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | Invoker invoker = new Invoker(); 10 | ConcreteReceiver receiver = new ConcreteReceiver(); 11 | 12 | invoker.executeCommand(new ConcreteCommand(), receiver); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/command/pattern/Command.java: -------------------------------------------------------------------------------- 1 | package command.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public abstract class Command { 7 | public abstract void execute(Receiver receiver); 8 | } 9 | -------------------------------------------------------------------------------- /src/command/pattern/ConcreteCommand.java: -------------------------------------------------------------------------------- 1 | package command.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public class ConcreteCommand extends Command { 7 | 8 | private Receiver receiver; 9 | 10 | @Override 11 | public void execute(Receiver receiver) { 12 | receiver.doAction(); 13 | this.receiver = receiver; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/command/pattern/ConcreteReceiver.java: -------------------------------------------------------------------------------- 1 | package command.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public class ConcreteReceiver extends Receiver { 7 | 8 | @Override 9 | public void doAction() { 10 | System.out.println("Action on CONCRETE receiver"); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/command/pattern/Invoker.java: -------------------------------------------------------------------------------- 1 | package command.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public class Invoker { 7 | public void executeCommand(Command command, Receiver receiver){ 8 | command.execute(receiver); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/command/pattern/Receiver.java: -------------------------------------------------------------------------------- 1 | package command.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 13/08/15. 5 | */ 6 | public abstract class Receiver { 7 | 8 | public abstract void doAction(); 9 | } 10 | -------------------------------------------------------------------------------- /src/composite/examples/directories/Directory.java: -------------------------------------------------------------------------------- 1 | package composite.examples.directories; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * Created by luisburgos on 18/07/15. 7 | */ 8 | public class Directory extends File { 9 | 10 | private ArrayList files; 11 | 12 | public Directory (String name) { 13 | this.name = name; 14 | files = new ArrayList<>(); 15 | } 16 | 17 | @Override 18 | public void add(File file) { 19 | files.add(file); 20 | } 21 | 22 | @Override 23 | public void remove(File file) { 24 | files.remove(file); 25 | } 26 | 27 | @Override 28 | public void showInfo() { 29 | System.out.print(identado.toString() + "* Directory: " + getName() + "\n"); 30 | identado.append(" "); 31 | for(File file : files){ 32 | file.showInfo(); 33 | } 34 | identado.setLength(identado.length() - 3); 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/composite/examples/directories/File.java: -------------------------------------------------------------------------------- 1 | package composite.examples.directories; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public abstract class File { 7 | 8 | protected String name; 9 | protected static StringBuffer identado = new StringBuffer(); 10 | 11 | public void add(File component) { 12 | throw new UnsupportedOperationException(); 13 | } 14 | 15 | public void remove(File component) { 16 | throw new UnsupportedOperationException(); 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void showInfo() { 24 | throw new UnsupportedOperationException(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/composite/examples/directories/FileSystem.java: -------------------------------------------------------------------------------- 1 | package composite.examples.directories; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public class FileSystem { 7 | 8 | private File allFiles; 9 | 10 | public FileSystem(File allFiles) { 11 | this.allFiles = allFiles; 12 | } 13 | 14 | public void printFiles() { 15 | allFiles.showInfo(); 16 | } 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/composite/examples/directories/FileSystemTestDrive.java: -------------------------------------------------------------------------------- 1 | package composite.examples.directories; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public class FileSystemTestDrive { 7 | 8 | public static void main(String[] args) { 9 | 10 | //Dummy linux file system. 11 | 12 | File home = new Directory("home"); 13 | File opt = new Directory("opt"); 14 | File usr = new Directory("usr"); 15 | 16 | File root = new Directory("root"); 17 | 18 | root.add(home); 19 | root.add(opt); 20 | root.add(usr); 21 | 22 | usr.add(new SimpleFile("bin")); 23 | usr.add(new SimpleFile("lib")); 24 | 25 | opt.add(new SimpleFile("google")); 26 | opt.add(new SimpleFile("idea")); 27 | opt.add(new SimpleFile("spotify")); 28 | 29 | home.add(new SimpleFile("luisburgos")); 30 | 31 | FileSystem fileSystem = new FileSystem(root); 32 | fileSystem.printFiles(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/composite/examples/directories/SimpleFile.java: -------------------------------------------------------------------------------- 1 | package composite.examples.directories; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public class SimpleFile extends File { 7 | 8 | public SimpleFile(String name) { 9 | this.name = name; 10 | } 11 | 12 | @Override 13 | public void showInfo() { 14 | System.out.print(identado.toString() + "-Simple File: " + getName() + "\n"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/composite/examples/menu/Client.java: -------------------------------------------------------------------------------- 1 | package composite.examples.menu; 2 | 3 | public class Client { 4 | 5 | private MenuComponent allMenus; 6 | 7 | public Client(MenuComponent todosLosMenus) { 8 | this.allMenus = todosLosMenus; 9 | } 10 | 11 | public void printMenu() { 12 | allMenus.print(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/composite/examples/menu/MenuComponent.java: -------------------------------------------------------------------------------- 1 | package composite.examples.menu; 2 | 3 | public abstract class MenuComponent { 4 | 5 | protected String name; 6 | protected static StringBuffer identado = new StringBuffer(); 7 | 8 | public void add(MenuComponent component) { 9 | throw new UnsupportedOperationException(); 10 | } 11 | 12 | public void remove(MenuComponent component) { 13 | throw new UnsupportedOperationException(); 14 | } 15 | 16 | public String getName() { 17 | throw new UnsupportedOperationException(); 18 | } 19 | 20 | public double getPrice() { 21 | throw new UnsupportedOperationException(); 22 | } 23 | 24 | public boolean isVegetarian() { 25 | throw new UnsupportedOperationException(); 26 | } 27 | 28 | public void print() { 29 | throw new UnsupportedOperationException(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/composite/examples/menu/MenuComposite.java: -------------------------------------------------------------------------------- 1 | package composite.examples.menu; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class MenuComposite extends MenuComponent { 6 | 7 | private ArrayList menuComponents; 8 | 9 | public MenuComposite(String name) { 10 | this.name = name; 11 | menuComponents = new ArrayList<>(); 12 | } 13 | 14 | @Override 15 | public void add(MenuComponent component) { 16 | this.menuComponents.add(component); 17 | } 18 | 19 | @Override 20 | public void remove(MenuComponent component) { 21 | this.menuComponents.remove(component); 22 | } 23 | 24 | @Override 25 | public String getName() { 26 | return this.name; 27 | } 28 | 29 | @Override 30 | public void print() { 31 | 32 | System.out.print(identado.toString() + "* " + getName() + "\n"); 33 | //System.out.println(identado.toString() + "---------------------"); 34 | identado.append(" "); 35 | for(MenuComponent menuComponent : menuComponents){ 36 | menuComponent.print(); 37 | } 38 | identado.setLength(identado.length() - 5); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/composite/examples/menu/MenuItem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | package composite.examples.menu; 7 | 8 | /** 9 | * 10 | * @author luisburgos 11 | */ 12 | public class MenuItem extends MenuComponent { 13 | 14 | private boolean vegetarian; 15 | private double price; 16 | 17 | public MenuItem(String name, boolean vegetarian, double price) { 18 | this.name = name; 19 | this.vegetarian = vegetarian; 20 | this.price = price; 21 | } 22 | 23 | @Override 24 | public String getName() { 25 | return this.name; 26 | } 27 | 28 | @Override 29 | public double getPrice() { 30 | return this.price; 31 | } 32 | 33 | @Override 34 | public boolean isVegetarian() { 35 | return this.vegetarian; 36 | } 37 | 38 | @Override 39 | public void print() { 40 | System.out.print(identado.toString() + "# " + getName()); 41 | if (isVegetarian()) { 42 | System.out.print("(v)"); 43 | } 44 | System.out.println("," + getPrice()); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/composite/examples/menu/MenuTestDrive.java: -------------------------------------------------------------------------------- 1 | package composite.examples.menu; 2 | 3 | public class MenuTestDrive { 4 | 5 | 6 | public static void main(String args[]) { 7 | 8 | MenuComponent meals = new MenuComposite("Comidas"); 9 | MenuComponent dinners = new MenuComposite("Cenas"); 10 | MenuComponent desserts = new MenuComposite("Postres"); 11 | MenuComponent mainCourse = new MenuComposite("Plato Fuerte"); 12 | 13 | MenuComponent allMenus = new MenuComposite("Menus"); 14 | 15 | allMenus.add(meals); 16 | allMenus.add(dinners); 17 | 18 | meals.add(mainCourse); 19 | meals.add(desserts); 20 | 21 | mainCourse.add(new MenuItem( 22 | "Crispy Chicken", 23 | false, 24 | 100.89) 25 | ); 26 | 27 | desserts.add(new MenuItem( 28 | "Apple Pie", 29 | false, 30 | 15.59) 31 | ); 32 | 33 | desserts.add(new MenuItem( 34 | "Cheesecake", 35 | false, 36 | 19.99) 37 | ); 38 | 39 | dinners.add(new MenuItem( 40 | "Hotdogs", 41 | false, 42 | 6.05) 43 | ); 44 | 45 | dinners.add(new MenuItem( 46 | "Spaghetti ", 47 | true, 48 | 30.89) 49 | ); 50 | 51 | 52 | //The client does not distinguish between item and composite 53 | Client client = new Client(allMenus); 54 | client.printMenu(); 55 | 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/composite/pattern/Component.java: -------------------------------------------------------------------------------- 1 | package composite.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public abstract class Component { 7 | 8 | protected String name; 9 | 10 | public void add(Component component) { 11 | throw new UnsupportedOperationException(); 12 | } 13 | public void remove(Component component) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | public abstract void doSomething(); 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/composite/pattern/Composite.java: -------------------------------------------------------------------------------- 1 | package composite.pattern; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * Created by luisburgos on 18/07/15. 7 | */ 8 | public class Composite extends Component{ 9 | 10 | private ArrayList components; 11 | 12 | public Composite(String name) { 13 | this.name = name; 14 | components = new ArrayList<>(); 15 | } 16 | 17 | @Override 18 | public void add(Component component) { 19 | components.add(component); 20 | } 21 | 22 | @Override 23 | public void remove(Component component) { 24 | components.remove(component); 25 | } 26 | 27 | @Override 28 | public void doSomething() { 29 | System.out.println(getName() + " doing something..."); 30 | for(Component component : components){ 31 | component.doSomething(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/composite/pattern/CompositeTest.java: -------------------------------------------------------------------------------- 1 | package composite.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public class CompositeTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | Component componentOne = new Composite("Composite One"); 11 | Component componentTwo = new Composite("Composite Two"); 12 | Component componentThree = new Composite("Composite Three"); 13 | 14 | Component componentWrapper = new Composite("All components"); 15 | 16 | componentWrapper.add(componentOne); 17 | componentWrapper.add(componentTwo); 18 | componentWrapper.add(componentThree); 19 | 20 | componentOne.add(new Leaf("ONE: Sub component one")); 21 | componentOne.add(new Leaf("ONE: Sub component two")); 22 | componentOne.add(new Leaf("ONE: Sub component three")); 23 | 24 | componentTwo.add(new Leaf("TWO: Sub component one")); 25 | componentTwo.add(new Leaf("TWO: Sub component two")); 26 | 27 | componentThree.add(new Leaf("THREE: Sub component one")); 28 | componentThree.add(new Leaf("THREE: Sub component two")); 29 | componentThree.add(new Leaf("THREE: Sub component three")); 30 | componentThree.add(new Leaf("THREE: Sub component four")); 31 | 32 | 33 | componentWrapper.doSomething(); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/composite/pattern/Leaf.java: -------------------------------------------------------------------------------- 1 | package composite.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 18/07/15. 5 | */ 6 | public class Leaf extends Component{ 7 | 8 | public Leaf(String name) { 9 | this.name = name; 10 | } 11 | 12 | @Override 13 | public void doSomething() { 14 | System.out.println(" " + getName() + " doing something..."); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/decorator/examples/pizzas/Mozzarella.java: -------------------------------------------------------------------------------- 1 | package decorator.examples.pizzas; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class Mozzarella extends ToppingDecorator { 7 | 8 | public Mozzarella(Pizza temporalPizza) { 9 | super(temporalPizza); 10 | System.out.println("Adding Mozzarella"); 11 | } 12 | 13 | @Override 14 | public String getDescription() { 15 | return temporalPizza.getDescription() + ", mozzarella"; 16 | } 17 | 18 | @Override 19 | public double getPrice() { 20 | System.out.println("Price of mozarrella: " + .50); 21 | return temporalPizza.getPrice() + .50; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/decorator/examples/pizzas/Pizza.java: -------------------------------------------------------------------------------- 1 | package decorator.examples.pizzas; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public interface Pizza { 7 | public String getDescription(); 8 | public double getPrice(); 9 | } 10 | -------------------------------------------------------------------------------- /src/decorator/examples/pizzas/PizzaMaker.java: -------------------------------------------------------------------------------- 1 | package decorator.examples.pizzas; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class PizzaMaker { 7 | 8 | public static void main(String[] args) { 9 | 10 | Pizza pizza = new Mozzarella(new TomatoSauce(new PlainPizza())); 11 | System.out.println("Ingredients: " + pizza.getDescription()); 12 | System.out.println("Total Price: " + pizza.getPrice()); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/decorator/examples/pizzas/PlainPizza.java: -------------------------------------------------------------------------------- 1 | package decorator.examples.pizzas; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class PlainPizza implements Pizza { 7 | 8 | public PlainPizza() { 9 | System.out.println("Adding Thin Dough"); 10 | } 11 | 12 | @Override 13 | public String getDescription() { 14 | return "Thin Dough"; 15 | } 16 | 17 | @Override 18 | public double getPrice() { 19 | System.out.println("Price of thin dough: " + 4.00); 20 | return 4.00; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/decorator/examples/pizzas/TomatoSauce.java: -------------------------------------------------------------------------------- 1 | package decorator.examples.pizzas; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class TomatoSauce extends ToppingDecorator { 7 | 8 | public TomatoSauce(Pizza temporalPizza) { 9 | super(temporalPizza); 10 | System.out.println("Adding Tomato Sauce"); 11 | } 12 | 13 | @Override 14 | public String getDescription() { 15 | return temporalPizza.getDescription() + ", tomato sauce"; 16 | } 17 | 18 | @Override 19 | public double getPrice() { 20 | System.out.println("Price of tomato sauce: " + 2.50); 21 | return temporalPizza.getPrice() + 2.50; 22 | } 23 | 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/decorator/examples/pizzas/ToppingDecorator.java: -------------------------------------------------------------------------------- 1 | package decorator.examples.pizzas; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public abstract class ToppingDecorator implements Pizza { 7 | 8 | protected Pizza temporalPizza; 9 | 10 | public ToppingDecorator(Pizza temporalPizza) { 11 | this.temporalPizza = temporalPizza; 12 | } 13 | 14 | @Override 15 | public String getDescription() { 16 | return temporalPizza.getDescription(); 17 | } 18 | 19 | @Override 20 | public double getPrice() { 21 | return temporalPizza.getPrice(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/decorator/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package decorator.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | 10 | Component component = new ConcreteDecoratorOne(new ConcreteComponent()); 11 | component.doOperation(); 12 | System.out.println("Adding concrete component two..."); 13 | component = new ConcreteDecoratorOne(new ConcreteDecoratorTwo(new ConcreteComponent())); 14 | component.doOperation(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/decorator/pattern/Component.java: -------------------------------------------------------------------------------- 1 | package decorator.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public interface Component { 7 | public void doOperation(); 8 | } 9 | -------------------------------------------------------------------------------- /src/decorator/pattern/ConcreteComponent.java: -------------------------------------------------------------------------------- 1 | package decorator.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class ConcreteComponent implements Component { 7 | 8 | @Override 9 | public void doOperation() { 10 | System.out.println("Concrete Component doing operation"); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/decorator/pattern/ConcreteDecoratorOne.java: -------------------------------------------------------------------------------- 1 | package decorator.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class ConcreteDecoratorOne extends Decorator { 7 | 8 | public ConcreteDecoratorOne(Component component) { 9 | super(component); 10 | } 11 | 12 | @Override 13 | public void doOperation() { 14 | super.doOperation(); 15 | doAdditionalOperation(); 16 | } 17 | 18 | public void doAdditionalOperation() { 19 | System.out.println("Doing additional operation concrete decorator ONE."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/decorator/pattern/ConcreteDecoratorTwo.java: -------------------------------------------------------------------------------- 1 | package decorator.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public class ConcreteDecoratorTwo extends Decorator{ 7 | 8 | public ConcreteDecoratorTwo(Component component) { 9 | super(component); 10 | } 11 | 12 | @Override 13 | public void doOperation() { 14 | super.doOperation(); 15 | doAdditionalOperation(); 16 | } 17 | 18 | public void doAdditionalOperation() { 19 | System.out.println("Doing additional operation concrete decorator TWO."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/decorator/pattern/Decorator.java: -------------------------------------------------------------------------------- 1 | package decorator.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 11/08/15. 5 | */ 6 | public abstract class Decorator implements Component { 7 | 8 | protected Component component; 9 | 10 | public Decorator(Component component){ 11 | this.component = component; 12 | } 13 | 14 | @Override 15 | public void doOperation() { 16 | component.doOperation(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/facade/examples/bank/AccountNumberCheck.java: -------------------------------------------------------------------------------- 1 | package facade.examples.bank; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class AccountNumberCheck { 7 | 8 | private int accountNumber = 1234567890; 9 | 10 | public int getAccountNumber() { return accountNumber; } 11 | 12 | public boolean isAccountActive(int accountNumberToCheck){ 13 | if(accountNumberToCheck == getAccountNumber()) { 14 | return true; 15 | } else { 16 | return false; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/facade/examples/bank/BankFacade.java: -------------------------------------------------------------------------------- 1 | package facade.examples.bank; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class BankFacade { 7 | 8 | private int accountNumber; 9 | private int securityCode; 10 | 11 | private AccountNumberCheck accountChecker; 12 | private SecurityCodeCheck codeChecker; 13 | private FundsCheck fundsChecker; 14 | 15 | private WelcomeMessage bankWelcome; 16 | 17 | public BankFacade(int accountNumber, int securityCode){ 18 | 19 | this.accountNumber = accountNumber; 20 | this.securityCode = securityCode; 21 | 22 | bankWelcome = new WelcomeMessage(); 23 | accountChecker = new AccountNumberCheck(); 24 | codeChecker = new SecurityCodeCheck(); 25 | fundsChecker = new FundsCheck(); 26 | 27 | } 28 | 29 | private int getAccountNumber() { return accountNumber; } 30 | 31 | private int getSecurityCode() { return securityCode; } 32 | 33 | public void withdrawCash(double cashAmount){ 34 | 35 | if(canWithdraw(cashAmount)) { 36 | System.out.println("Transaction Complete\n"); 37 | } else { 38 | System.out.println("Transaction Failed\n"); 39 | } 40 | 41 | } 42 | 43 | 44 | public void depositCash(double cashAmount){ 45 | if(canDeposit(cashAmount)) { 46 | fundsChecker.makeDeposit(cashAmount); 47 | System.out.println("Transaction Complete\n"); 48 | } else { 49 | System.out.println("Transaction Failed\n"); 50 | } 51 | } 52 | 53 | private boolean canWithdraw(double cashAmount){ 54 | return accountChecker.isAccountActive(getAccountNumber()) && 55 | codeChecker.isCodeCorrect(getSecurityCode()) && 56 | fundsChecker.haveEnoughMoney(cashAmount); 57 | } 58 | 59 | private boolean canDeposit(double cashAmount){ 60 | return accountChecker.isAccountActive(getAccountNumber()) && 61 | codeChecker.isCodeCorrect(getSecurityCode()); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/facade/examples/bank/Client.java: -------------------------------------------------------------------------------- 1 | package facade.examples.bank; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | 10 | BankFacade accesingBank = new BankFacade(1234567890, 1234); 11 | 12 | accesingBank.withdrawCash(50.00); 13 | accesingBank.withdrawCash(900.00); 14 | accesingBank.depositCash(200.00); 15 | 16 | accesingBank.withdrawCash(900.00); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/facade/examples/bank/FundsCheck.java: -------------------------------------------------------------------------------- 1 | package facade.examples.bank; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class FundsCheck { 7 | 8 | private double cashInAccount = 1000.00; 9 | 10 | public double getCashInAccount() { return cashInAccount; } 11 | 12 | public void decreaseCashInAccount(double cashWithdrawn) { cashInAccount -= cashWithdrawn; } 13 | 14 | public void increaseCashInAccount(double cashDeposited) { cashInAccount += cashDeposited; } 15 | 16 | public boolean haveEnoughMoney(double cashToWithdrawal) { 17 | 18 | if(cashToWithdrawal > getCashInAccount()) { 19 | System.out.println("Error: You don't have enough money"); 20 | System.out.println("Current Balance: " + getCashInAccount()); 21 | return false; 22 | } else { 23 | decreaseCashInAccount(cashToWithdrawal); 24 | System.out.println("Withdrawal Complete: Current Balance is " + getCashInAccount()); 25 | return true; 26 | } 27 | 28 | } 29 | 30 | public void makeDeposit(double cashToDeposit) { 31 | increaseCashInAccount(cashToDeposit); 32 | System.out.println("Deposit Complete: Current Balance is " + getCashInAccount()); 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/facade/examples/bank/SecurityCodeCheck.java: -------------------------------------------------------------------------------- 1 | package facade.examples.bank; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class SecurityCodeCheck { 7 | 8 | private int securityCode = 1234; 9 | 10 | public int getSecurityCode() { return securityCode; } 11 | 12 | public boolean isCodeCorrect(int securityCode){ 13 | 14 | if(securityCode == getSecurityCode()) { 15 | return true; 16 | } else { 17 | return false; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/facade/examples/bank/WelcomeMessage.java: -------------------------------------------------------------------------------- 1 | package facade.examples.bank; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class WelcomeMessage { 7 | public WelcomeMessage(){ 8 | System.out.println("Welcome to this BANK."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/facade/examples/computer/CPU.java: -------------------------------------------------------------------------------- 1 | package facade.examples.computer; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class CPU { 7 | public void freeze() { 8 | System.out.println("CPU: Freezing..."); 9 | } 10 | 11 | public void execute() { 12 | System.out.println("CPU: Executing..."); 13 | } 14 | 15 | public void jump() { 16 | System.out.println("CPU: Jumping..."); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/facade/examples/computer/ComputerFacade.java: -------------------------------------------------------------------------------- 1 | package facade.examples.computer; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class ComputerFacade { 7 | 8 | private CPU cpu; 9 | private HardDrive hardDrive; 10 | private Memory memory; 11 | 12 | public ComputerFacade(){ 13 | this.cpu = new CPU(); 14 | this.hardDrive = new HardDrive(); 15 | this.memory = new Memory(); 16 | } 17 | 18 | public void start(){ 19 | System.out.println("STARTING..."); 20 | cpu.freeze(); 21 | memory.load(); 22 | hardDrive.read(); 23 | cpu.jump(); 24 | cpu.execute(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/facade/examples/computer/HardDrive.java: -------------------------------------------------------------------------------- 1 | package facade.examples.computer; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class HardDrive { 7 | public void read() { 8 | System.out.println("HARD DRIVE: Reading..."); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/facade/examples/computer/Memory.java: -------------------------------------------------------------------------------- 1 | package facade.examples.computer; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class Memory { 7 | public void load() { 8 | System.out.println("MEMORY: Loading..."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/facade/examples/computer/User.java: -------------------------------------------------------------------------------- 1 | package facade.examples.computer; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class User { 7 | 8 | public static void main(String[] args) { 9 | ComputerFacade computer = new ComputerFacade(); 10 | computer.start(); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/facade/pattern/Action.java: -------------------------------------------------------------------------------- 1 | package facade.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public interface Action { 7 | public void doSomething(); 8 | } 9 | -------------------------------------------------------------------------------- /src/facade/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package facade.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | 10 | Facade facade = new Facade(); 11 | facade.doSomethingInOne(); 12 | facade.doSomethingInOTwo(); 13 | facade.doSomethingInOneAndTwo(); 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/facade/pattern/ConcreteActionOne.java: -------------------------------------------------------------------------------- 1 | package facade.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class ConcreteActionOne implements Action { 7 | @Override 8 | public void doSomething() { 9 | System.out.println("\tDoing something in action One"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/facade/pattern/ConcreteActionTwo.java: -------------------------------------------------------------------------------- 1 | package facade.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class ConcreteActionTwo implements Action { 7 | @Override 8 | public void doSomething() { 9 | System.out.println("\tDoing something in action TWO"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/facade/pattern/Facade.java: -------------------------------------------------------------------------------- 1 | package facade.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/08/15. 5 | */ 6 | public class Facade { 7 | 8 | private ConcreteActionOne one; 9 | private ConcreteActionTwo two; 10 | 11 | public Facade() { 12 | System.out.println("This is the FACADE pattern..."); 13 | this.one = new ConcreteActionOne(); 14 | this.two = new ConcreteActionTwo(); 15 | } 16 | 17 | public void doSomethingInOne() { 18 | System.out.println("Calling doSomething in action ONE:"); 19 | one.doSomething(); 20 | } 21 | 22 | public void doSomethingInOTwo() { 23 | System.out.println("Calling doSomething in action TWO:"); 24 | two.doSomething(); 25 | } 26 | 27 | public void doSomethingInOneAndTwo() { 28 | System.out.println("Calling doSomething in action ONE and TWO:"); 29 | one.doSomething(); 30 | two.doSomething(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/factory/examples/cars/CarsFactoryTestDrive.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars; 2 | 3 | import factory.examples.cars.factories.CarsFactory; 4 | import factory.examples.cars.factories.NissanFactory; 5 | import factory.examples.cars.factories.ToyotaFactory; 6 | import factory.examples.cars.products.Car; 7 | 8 | /** 9 | * Created by luisburgos on 15/07/15. 10 | */ 11 | public class CarsFactoryTestDrive { 12 | 13 | public static void main(String[] args) { 14 | 15 | CarsFactory factory; 16 | Car carCreated; 17 | 18 | factory = new NissanFactory(); 19 | 20 | System.out.println("For Tsuru:"); 21 | carCreated = factory.createProduct("tsuru"); 22 | if(carCreated != null){ 23 | System.out.println(carCreated.getInformation()); 24 | }else{ 25 | System.out.println("No product created."); 26 | } 27 | 28 | System.out.println("For Versa:"); 29 | carCreated = factory.createProduct("versa"); 30 | if(carCreated != null){ 31 | System.out.println(carCreated.getInformation()); 32 | }else{ 33 | System.out.println("No product created."); 34 | } 35 | 36 | factory = new ToyotaFactory(); 37 | 38 | System.out.println("For Corolla:"); 39 | carCreated = factory.createProduct("corolla"); 40 | if(carCreated != null){ 41 | System.out.println(carCreated.getInformation()); 42 | }else{ 43 | System.out.println("No product created."); 44 | } 45 | 46 | System.out.println("For Camry:"); 47 | carCreated = factory.createProduct("camry"); 48 | if(carCreated != null){ 49 | System.out.println(carCreated.getInformation()); 50 | }else{ 51 | System.out.println("No product created."); 52 | } 53 | 54 | System.out.println("For Spark:"); 55 | carCreated = factory.createProduct("spark"); 56 | if(carCreated != null){ 57 | System.out.println(carCreated.getInformation()); 58 | }else{ 59 | System.out.println("No product created."); 60 | } 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/factory/examples/cars/factories/CarsFactory.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.factories; 2 | 3 | import factory.examples.cars.products.Car; 4 | 5 | /** 6 | * Created by luisburgos on 15/07/15. 7 | */ 8 | public abstract class CarsFactory { 9 | public abstract Car createProduct(String productName); 10 | } 11 | -------------------------------------------------------------------------------- /src/factory/examples/cars/factories/NissanFactory.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.factories; 2 | 3 | import factory.examples.cars.products.*; 4 | 5 | /** 6 | * Created by luisburgos on 15/07/15. 7 | */ 8 | public class NissanFactory extends CarsFactory { 9 | @Override 10 | public Car createProduct(String productName) { 11 | Car car = null; 12 | 13 | if(productName.equalsIgnoreCase("TSURU")){ 14 | car = new Tsuru(); 15 | }else if(productName.equalsIgnoreCase("VERSA")){ 16 | car = new Versa(); 17 | } 18 | 19 | return car; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/factory/examples/cars/factories/ToyotaFactory.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.factories; 2 | 3 | import factory.examples.cars.products.Camry; 4 | import factory.examples.cars.products.Car; 5 | import factory.examples.cars.products.Corolla; 6 | 7 | /** 8 | * Created by luisburgos on 15/07/15. 9 | */ 10 | public class ToyotaFactory extends CarsFactory { 11 | @Override 12 | public Car createProduct(String productName) { 13 | Car car = null; 14 | 15 | if(productName.equalsIgnoreCase("CAMRY")){ 16 | car = new Camry(); 17 | }else if(productName.equalsIgnoreCase("COROLLA")){ 18 | car = new Corolla(); 19 | } 20 | 21 | return car; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/factory/examples/cars/products/Camry.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.products; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class Camry extends Car { 7 | 8 | public Camry(){ 9 | setName("Camry"); 10 | setAgency("Toyota"); 11 | setPrice(200000); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/factory/examples/cars/products/Car.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.products; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public abstract class Car { 7 | 8 | private String agency; 9 | private String name; 10 | private double price; 11 | 12 | public Car(){} 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public String getPrice() { 23 | return String.format( "$%.2f", price); 24 | } 25 | 26 | public void setPrice(double price) { 27 | this.price = price; 28 | } 29 | 30 | public String getAgency() { 31 | return agency; 32 | } 33 | 34 | public void setAgency(String agency) { 35 | this.agency = agency; 36 | } 37 | 38 | public String getInformation(){ 39 | return "Agency: " + getAgency() + ", Name: " + getName() + ", Price: " + getPrice(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/factory/examples/cars/products/Corolla.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.products; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class Corolla extends Car { 7 | 8 | public Corolla(){ 9 | setName("Corolla"); 10 | setAgency("Toyota"); 11 | setPrice(300000); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/factory/examples/cars/products/Tsuru.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.products; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class Tsuru extends Car { 7 | 8 | public Tsuru(){ 9 | setName("Tsuru"); 10 | setAgency("Nissan"); 11 | setPrice(150000); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/factory/examples/cars/products/Versa.java: -------------------------------------------------------------------------------- 1 | package factory.examples.cars.products; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class Versa extends Car { 7 | 8 | public Versa(){ 9 | setName("Versa"); 10 | setAgency("Nissan"); 11 | setPrice(350000); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/factory/examples/ships/EnemyShipFactory.java: -------------------------------------------------------------------------------- 1 | package factory.examples.ships; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class EnemyShipFactory implements ShipFactory{ 7 | @Override 8 | public Ship createShip(String shipType) { 9 | Ship ship = null; 10 | 11 | if(shipType.equalsIgnoreCase("rocket")){ 12 | ship = new RocketShip(); 13 | }else if(shipType.equalsIgnoreCase("ufo")){ 14 | ship = new UFOShip(); 15 | } 16 | 17 | return ship; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/factory/examples/ships/RocketShip.java: -------------------------------------------------------------------------------- 1 | package factory.examples.ships; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class RocketShip extends Ship { 7 | 8 | public RocketShip (){ 9 | setName("Rocket Ship"); 10 | setDamage(10); 11 | setSpeed(1000); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/factory/examples/ships/Ship.java: -------------------------------------------------------------------------------- 1 | package factory.examples.ships; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public abstract class Ship { 7 | 8 | private String name; 9 | private double speed; 10 | private double damage; 11 | 12 | public Ship() { 13 | } 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public void setName(String name) { 20 | 21 | this.name = name; 22 | } 23 | 24 | public double getSpeed() { 25 | return speed; 26 | } 27 | 28 | public void setSpeed(double speed) { 29 | this.speed = speed; 30 | } 31 | 32 | public double getDamage() { 33 | return damage; 34 | } 35 | 36 | public void setDamage(double damage) { 37 | this.damage = damage; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return "Name: " + getName() + "| Damage: " + String.format("%.2f", getDamage()) + "| Speed:" + String.format("%.2f", getSpeed()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/factory/examples/ships/ShipFactory.java: -------------------------------------------------------------------------------- 1 | package factory.examples.ships; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public interface ShipFactory { 7 | public Ship createShip(String shipType); 8 | } 9 | -------------------------------------------------------------------------------- /src/factory/examples/ships/ShipTestDrive.java: -------------------------------------------------------------------------------- 1 | package factory.examples.ships; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class ShipTestDrive { 7 | 8 | public static void main(String[] args) { 9 | 10 | ShipFactory shipFactory = new EnemyShipFactory(); 11 | Ship shipCreated; 12 | 13 | System.out.println("ROCKET: "); 14 | shipCreated = shipFactory.createShip("rocket"); 15 | if(shipCreated!= null){ 16 | System.out.println(shipCreated.toString()); 17 | }else{ 18 | System.out.println("No ship created."); 19 | } 20 | 21 | System.out.println("UFO: "); 22 | shipCreated = shipFactory.createShip("UFO"); 23 | if(shipCreated!= null){ 24 | System.out.println(shipCreated.toString()); 25 | }else{ 26 | System.out.println("No ship created."); 27 | } 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/factory/examples/ships/UFOShip.java: -------------------------------------------------------------------------------- 1 | package factory.examples.ships; 2 | 3 | /** 4 | * Created by luisburgos on 16/07/15. 5 | */ 6 | public class UFOShip extends Ship { 7 | 8 | public UFOShip (){ 9 | setName("UFO Ship"); 10 | setDamage(30); 11 | setSpeed(3000); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/factory/pattern/ConcreteFactoryOne.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class ConcreteFactoryOne extends Factory{ 7 | 8 | @Override 9 | public Product createProduct(String productType) { 10 | return new ConcreteProductOne(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/factory/pattern/ConcreteFactoryTwo.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class ConcreteFactoryTwo extends Factory{ 7 | @Override 8 | public Product createProduct(String productType) { 9 | return new ConcreteProductTwo(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/factory/pattern/ConcreteProductOne.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class ConcreteProductOne extends Product{ 7 | 8 | public ConcreteProductOne(String name, String description){ 9 | setName(name); 10 | setDescription(description); 11 | } 12 | 13 | public ConcreteProductOne(){ 14 | setName("Product One"); 15 | setDescription("Description of product one"); 16 | } 17 | 18 | @Override 19 | public String getInformation() { 20 | return "Product name: " + getName() + " , Description: " + getDescription(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/factory/pattern/ConcreteProductTwo.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class ConcreteProductTwo extends Product { 7 | 8 | public ConcreteProductTwo(String name, String description){ 9 | setName(name); 10 | setDescription(description); 11 | } 12 | 13 | public ConcreteProductTwo(){ 14 | setName("Product Two"); 15 | setDescription("Description of product two"); 16 | } 17 | 18 | @Override 19 | public String getInformation() { 20 | return "Product name: " + getName() + " , Description: " + getDescription(); 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/factory/pattern/Factory.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public abstract class Factory { 7 | public abstract Product createProduct(String productType); 8 | } 9 | -------------------------------------------------------------------------------- /src/factory/pattern/FactoryTestDrive.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class FactoryTestDrive { 7 | 8 | public static void main(String[] args) { 9 | 10 | Factory factory; 11 | Product productCreated; 12 | 13 | factory = new ConcreteFactoryOne(); 14 | 15 | productCreated = factory.createProduct("one"); 16 | 17 | if(productCreated != null){ 18 | System.out.println(productCreated.getInformation()); 19 | }else{ 20 | System.out.println("No product created."); 21 | } 22 | 23 | factory = new ConcreteFactoryTwo(); 24 | 25 | productCreated = factory.createProduct("two"); 26 | 27 | if(productCreated != null){ 28 | System.out.println(productCreated.getInformation()); 29 | }else{ 30 | System.out.println("No product created."); 31 | } 32 | 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/factory/pattern/Product.java: -------------------------------------------------------------------------------- 1 | package factory.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public abstract class Product { 7 | 8 | private String name; 9 | private String description; 10 | 11 | public Product(){} 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public void setName(String name) { 18 | this.name = name; 19 | } 20 | 21 | public String getDescription() { 22 | return description; 23 | } 24 | 25 | public void setDescription(String description) { 26 | this.description = description; 27 | } 28 | 29 | public abstract String getInformation(); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/flyweight/examples/counterstrike/CounterStrikeTest.java: -------------------------------------------------------------------------------- 1 | package flyweight.examples.counterstrike; 2 | 3 | import java.util.Random; 4 | 5 | public class CounterStrikeTest { 6 | 7 | private static String[] playerType = {"Terrorist", "CounterTerrorist"}; 8 | private static String[] weapons = {"AK-47", "Maverick", "Gut Knife", "Desert Eagle"}; 9 | 10 | public static void main(String args[]) { 11 | for (int i = 0; i < 10; i++) { 12 | Player p = PlayerFactory.getPlayer(getRandPlayerType()); 13 | p.assignWeapon(getRandWeapon()); 14 | p.mission(); 15 | } 16 | } 17 | 18 | // Utility methods to get a random player type and weapon 19 | public static String getRandPlayerType() { 20 | Random r = new Random(); 21 | int randInt = r.nextInt(playerType.length); 22 | 23 | return playerType[randInt]; 24 | } 25 | 26 | public static String getRandWeapon() { 27 | Random r = new Random(); 28 | int randInt = r.nextInt(weapons.length); 29 | 30 | return weapons[randInt]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/flyweight/examples/counterstrike/CounterTerrorist.java: -------------------------------------------------------------------------------- 1 | package flyweight.examples.counterstrike; 2 | 3 | public class CounterTerrorist implements Player { 4 | // Intrinsic Attribute 5 | private final String TASK; 6 | 7 | // Extrinsic Attribute 8 | private String weapon; 9 | 10 | public CounterTerrorist() { 11 | TASK = "DIFFUSE BOMB"; 12 | } 13 | 14 | public void assignWeapon(String weapon) { 15 | this.weapon = weapon; 16 | } 17 | 18 | public void mission() { 19 | System.out.println("["+System.identityHashCode(this) + "] Counter Terrorist with weapon " + weapon + " | Task is " + TASK); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/flyweight/examples/counterstrike/Player.java: -------------------------------------------------------------------------------- 1 | package flyweight.examples.counterstrike; 2 | 3 | public interface Player { 4 | public void assignWeapon(String weapon); 5 | public void mission(); 6 | } 7 | -------------------------------------------------------------------------------- /src/flyweight/examples/counterstrike/PlayerFactory.java: -------------------------------------------------------------------------------- 1 | package flyweight.examples.counterstrike; 2 | 3 | import java.util.HashMap; 4 | 5 | public class PlayerFactory { 6 | 7 | private static HashMap hm = new HashMap(); 8 | 9 | // Method to get a player 10 | public static Player getPlayer(String type) { 11 | Player p = null; 12 | 13 | /* If an object for TS or CT has already been 14 | created simply return its reference */ 15 | if (hm.containsKey(type)) { 16 | 17 | p = hm.get(type); 18 | 19 | }else { 20 | switch(type){ 21 | case "Terrorist": 22 | System.out.println("Terrorist Created"); 23 | p = new Terrorist(); 24 | break; 25 | case "CounterTerrorist": 26 | System.out.println("Counter Terrorist Created"); 27 | p = new CounterTerrorist(); 28 | break; 29 | default : 30 | System.out.println("Unreachable code!"); 31 | } 32 | 33 | // Once created insert it into the HashMap 34 | hm.put(type, p); 35 | } 36 | return p; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/flyweight/examples/counterstrike/Terrorist.java: -------------------------------------------------------------------------------- 1 | package flyweight.examples.counterstrike; 2 | 3 | public class Terrorist implements Player { 4 | // Intrinsic Attribute 5 | private final String TASK; 6 | 7 | // Extrinsic Attribute 8 | private String weapon; 9 | 10 | public Terrorist() { 11 | TASK = "PLANT A BOMB"; 12 | } 13 | 14 | public void assignWeapon(String weapon) { 15 | this.weapon = weapon; 16 | } 17 | 18 | public void mission() { 19 | System.out.println("["+System.identityHashCode(this) + "] Terrorist with weapon " + weapon + " | Task is " + TASK); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/Context.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.function.Function; 9 | import java.util.function.Predicate; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.Stream; 12 | 13 | public class Context { 14 | 15 | private static Map> tables = new HashMap<>(); 16 | 17 | static { 18 | List list = new ArrayList<>(); 19 | list.add(new Row("John", "Doe")); 20 | list.add(new Row("Jan", "Kowalski")); 21 | list.add(new Row("Dominic", "Doom")); 22 | 23 | tables.put("people", list); 24 | } 25 | 26 | private String table; 27 | private String column; 28 | 29 | /** 30 | * Index of column to be shown in result. 31 | * Calculated in {@link #setColumnMapper()} 32 | */ 33 | private int colIndex = -1; 34 | 35 | /** 36 | * Default setup, used for clearing the context for next queries. 37 | * See {@link Context#clear()} 38 | */ 39 | private static final Predicate matchAnyString = s -> s.length() > 0; 40 | private static final Function> matchAllColumns = Stream::of; 41 | /** 42 | * Varies based on setup in subclasses of {@link Expression} 43 | */ 44 | private Predicate whereFilter = matchAnyString; 45 | private Function> columnMapper = matchAllColumns; 46 | 47 | void setColumn(String column) { 48 | this.column = column; 49 | setColumnMapper(); 50 | } 51 | 52 | void setTable(String table) { 53 | this.table = table; 54 | } 55 | 56 | void setFilter(Predicate filter) { 57 | whereFilter = filter; 58 | } 59 | 60 | /** 61 | * Clears the context to defaults. 62 | * No filters, match all columns. 63 | */ 64 | void clear() { 65 | column = ""; 66 | columnMapper = matchAllColumns; 67 | whereFilter = matchAnyString; 68 | } 69 | 70 | List search() { 71 | 72 | List result = tables.entrySet() 73 | .stream() 74 | .filter(entry -> entry.getKey().equalsIgnoreCase(table)) 75 | .flatMap(entry -> Stream.of(entry.getValue())) 76 | .flatMap(Collection::stream) 77 | .map(Row::toString) 78 | .flatMap(columnMapper) 79 | .filter(whereFilter) 80 | .collect(Collectors.toList()); 81 | 82 | clear(); 83 | 84 | return result; 85 | } 86 | 87 | /** 88 | * Sets column mapper based on {@link #column} attribute. 89 | * Note: If column is unknown, will remain to look for all columns. 90 | */ 91 | private void setColumnMapper() { 92 | switch (column) { 93 | case "*": 94 | colIndex = -1; 95 | break; 96 | case "name": 97 | colIndex = 0; 98 | break; 99 | case "surname": 100 | colIndex = 1; 101 | break; 102 | } 103 | if (colIndex != -1) { 104 | columnMapper = s -> Stream.of(s.split(" ")[colIndex]); 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/Demo.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | import java.util.List; 4 | 5 | public class Demo { 6 | 7 | public static void main(String[] args) { 8 | 9 | Expression query = new Select("name", new From("people")); 10 | Context ctx = new Context(); 11 | List result = query.interpret(ctx); 12 | System.out.println(result); 13 | 14 | Expression query2 = new Select("*", new From("people")); 15 | List result2 = query2.interpret(ctx); 16 | System.out.println(result2); 17 | 18 | Expression query3 = new Select("name", new From("people", new Where(name -> name.toLowerCase().startsWith("d")))); 19 | List result3 = query3.interpret(ctx); 20 | System.out.println(result3); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/Expression.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | import java.util.List; 4 | 5 | public interface Expression { 6 | List interpret(Context ctx); 7 | } 8 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/From.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | import java.util.List; 4 | 5 | public class From implements Expression { 6 | 7 | private String table; 8 | private Where where; 9 | 10 | From(String table) { 11 | this.table = table; 12 | } 13 | 14 | From(String table, Where where) { 15 | this.table = table; 16 | this.where = where; 17 | } 18 | 19 | @Override 20 | public List interpret(Context ctx) { 21 | ctx.setTable(table); 22 | if (where == null) { 23 | return ctx.search(); 24 | } 25 | return where.interpret(ctx); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/Row.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | public class Row { 4 | private String name; 5 | private String surname; 6 | 7 | Row(String name, String surname) { 8 | this.name = name; 9 | this.surname = surname; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return name + " " + surname; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/Select.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | import java.util.List; 4 | 5 | public class Select implements Expression { 6 | 7 | private String column; 8 | private From from; 9 | 10 | Select(String column, From from) { 11 | this.column = column; 12 | this.from = from; 13 | } 14 | 15 | @Override 16 | public List interpret(Context ctx) { 17 | ctx.setColumn(column); 18 | return from.interpret(ctx); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/interpreter/examples/sql/Where.java: -------------------------------------------------------------------------------- 1 | package interpreter.examples.sql; 2 | 3 | import java.util.List; 4 | import java.util.function.Predicate; 5 | 6 | public class Where implements Expression { 7 | 8 | private Predicate filter; 9 | 10 | Where(Predicate filter) { 11 | this.filter = filter; 12 | } 13 | 14 | @Override 15 | public List interpret(Context ctx) { 16 | ctx.setFilter(filter); 17 | return ctx.search(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/Client.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public class Client { 4 | 5 | public static void main(String args[]) { 6 | NotificationBar nb = new NotificationBar(); 7 | nb.printNotifications(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/Collection.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public interface Collection { 4 | public Iterator createIterator(); 5 | } 6 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/Iterator.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public interface Iterator { 4 | boolean hasNext(); 5 | 6 | Object next(); 7 | } 8 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/Notification.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public class Notification { 4 | String notification; 5 | 6 | public Notification(String notification) { 7 | this.notification = notification; 8 | } 9 | public String getNotification() { 10 | return notification; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/NotificationBar.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public class NotificationBar { 4 | NotificationCollection notifications; 5 | 6 | public NotificationBar() { 7 | this.notifications = new NotificationCollection(); 8 | } 9 | 10 | public void printNotifications() { 11 | Iterator iterator = notifications.createIterator(); 12 | System.out.println("-------NOTIFICATION BAR------------"); 13 | while (iterator.hasNext()) { 14 | Notification n = (Notification)iterator.next(); 15 | System.out.println(n.getNotification()); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/NotificationCollection.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public class NotificationCollection implements Collection { 4 | 5 | static final int MAX_ITEMS = 6; 6 | int numberOfItems = 0; 7 | Notification[] notificationList; 8 | 9 | public NotificationCollection() { 10 | notificationList = new Notification[MAX_ITEMS]; 11 | 12 | // Let us add some dummy notifications 13 | addItem("Notification 1"); 14 | addItem("Notification 2"); 15 | addItem("Notification 3"); 16 | } 17 | 18 | public void addItem(String str) { 19 | Notification notification = new Notification(str); 20 | if (numberOfItems >= MAX_ITEMS) { 21 | System.err.println("Full"); 22 | } else { 23 | notificationList[numberOfItems] = notification; 24 | numberOfItems = numberOfItems + 1; 25 | } 26 | } 27 | 28 | public Iterator createIterator() { 29 | return new NotificationIterator(notificationList); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/iterator/examples/notifications/NotificationIterator.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.notifications; 2 | 3 | public class NotificationIterator implements Iterator { 4 | Notification[] notificationList; 5 | 6 | int pos = 0; 7 | 8 | public NotificationIterator (Notification[] notificationList) { 9 | this.notificationList = notificationList; 10 | } 11 | 12 | public Object next() { 13 | Notification notification = notificationList[pos]; 14 | pos += 1; 15 | return notification; 16 | } 17 | 18 | public boolean hasNext() { 19 | if (pos >= notificationList.length || 20 | notificationList[pos] == null) { 21 | return false; 22 | } else { 23 | return true; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/iterator/examples/vectors/Client.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.vectors; 2 | 3 | public class Client { 4 | public static void main(String argv[]) { 5 | Vector vector = new Vector(5); 6 | 7 | //Creación del iterador 8 | VectorIterator iterador = vector.iterador(); 9 | 10 | //Recorrido con el iterador 11 | while (iterador.hasNext()) 12 | System.out.println(iterador.next()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/iterator/examples/vectors/Vector.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.vectors; 2 | 3 | public class Vector { 4 | public int[] _datos; 5 | 6 | public Vector(int valores){ 7 | _datos = new int[valores]; 8 | for (int i = 0; i < _datos.length; i++){ 9 | _datos[i] = i; 10 | } 11 | } 12 | 13 | public int getValor(int pos){ 14 | return _datos[pos]; 15 | } 16 | 17 | public void setValor(int pos, int valor){ 18 | _datos[pos] = valor; 19 | } 20 | 21 | public int dimension(){ 22 | return _datos.length; 23 | } 24 | 25 | public VectorIterator iterador(){ 26 | return new VectorIterator(this); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/iterator/examples/vectors/VectorIterator.java: -------------------------------------------------------------------------------- 1 | package iterator.examples.vectors; 2 | 3 | public class VectorIterator { 4 | private int[] _vector; 5 | private int _posicion; 6 | 7 | public VectorIterator(Vector vector) { 8 | _vector = vector._datos; 9 | _posicion = 0; 10 | } 11 | 12 | public boolean hasNext(){ 13 | if (_posicion < _vector.length) 14 | return true; 15 | else 16 | return false; 17 | } 18 | 19 | public Object next(){ 20 | int valor = _vector[_posicion]; 21 | _posicion++; 22 | return valor; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/mediator/examples/airtrafficcontroller/Client.java: -------------------------------------------------------------------------------- 1 | package mediator.examples.airtrafficcontroller; 2 | 3 | public class Client { 4 | 5 | public static void main(String args[]) { 6 | 7 | ControlTower mediator = new ControlTower(); 8 | 9 | Flight sparrow101 = new Flight(mediator); 10 | Runway mainRunway = new Runway(mediator); 11 | 12 | mediator.registerFlight(sparrow101); 13 | mediator.registerRunway(mainRunway); 14 | 15 | sparrow101.getReady(); 16 | 17 | mainRunway.land(); 18 | sparrow101.land(); 19 | } 20 | } -------------------------------------------------------------------------------- /src/mediator/examples/airtrafficcontroller/Command.java: -------------------------------------------------------------------------------- 1 | package mediator.examples.airtrafficcontroller; 2 | 3 | interface Command{ 4 | void land(); 5 | } -------------------------------------------------------------------------------- /src/mediator/examples/airtrafficcontroller/ControlTower.java: -------------------------------------------------------------------------------- 1 | package mediator.examples.airtrafficcontroller; 2 | 3 | public class ControlTower { 4 | private Flight flight; 5 | private Runway runway; 6 | public boolean land; 7 | 8 | public void registerRunway(Runway runway) { 9 | this.runway = runway; 10 | } 11 | 12 | public void registerFlight(Flight flight) { 13 | this.flight = flight; 14 | } 15 | 16 | public boolean isLandingOk() { 17 | return land; 18 | } 19 | 20 | public void setLandingStatus(boolean status) { 21 | land = status; 22 | } 23 | } -------------------------------------------------------------------------------- /src/mediator/examples/airtrafficcontroller/Flight.java: -------------------------------------------------------------------------------- 1 | package mediator.examples.airtrafficcontroller; 2 | 3 | public class Flight implements Command { 4 | private ControlTower mediator; 5 | 6 | public Flight(ControlTower mediator) { 7 | this.mediator = mediator; 8 | } 9 | 10 | public void land() { 11 | if (mediator.isLandingOk()) { 12 | System.out.println("Successfully Landed."); 13 | mediator.setLandingStatus(true); 14 | 15 | } else { 16 | System.out.println("Waiting for landing."); 17 | } 18 | } 19 | 20 | public void getReady() { 21 | System.out.println("Ready for landing."); 22 | } 23 | } -------------------------------------------------------------------------------- /src/mediator/examples/airtrafficcontroller/Runway.java: -------------------------------------------------------------------------------- 1 | package mediator.examples.airtrafficcontroller; 2 | 3 | public class Runway implements Command { 4 | private ControlTower mediator; 5 | 6 | public Runway(ControlTower mediator) { 7 | this.mediator = mediator; 8 | mediator.setLandingStatus(false); 9 | } 10 | 11 | @Override 12 | public void land() { 13 | System.out.println("Landing permission granted."); 14 | mediator.setLandingStatus(true); 15 | } 16 | } -------------------------------------------------------------------------------- /src/memento/examples/timemachine/Life.java: -------------------------------------------------------------------------------- 1 | package memento.examples.timemachine; 2 | 3 | public class Life { 4 | private String time; 5 | 6 | public void set(String time) { 7 | System.out.println("Setting time to " + time); 8 | this.time = time; 9 | } 10 | 11 | public Memento saveToMemento() { 12 | System.out.println("Saving time to Memento"); 13 | return new Memento(time); 14 | } 15 | 16 | public void restoreFromMemento(Memento memento) { 17 | time = memento.getSavedTime(); 18 | System.out.println("Time restored from Memento: " + time); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/memento/examples/timemachine/Memento.java: -------------------------------------------------------------------------------- 1 | package memento.examples.timemachine; 2 | 3 | public class Memento { 4 | 5 | private final String time; 6 | 7 | public Memento(String timeToSave) { 8 | time = timeToSave; 9 | } 10 | 11 | public String getSavedTime() { 12 | return time; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/memento/examples/timemachine/TimeMachineClient.java: -------------------------------------------------------------------------------- 1 | package memento.examples.timemachine; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class TimeMachineClient { 7 | 8 | public static void main(String[] args) { 9 | 10 | List savedTimes = new ArrayList(); 11 | 12 | Life life = new Life(); 13 | 14 | //time travel and record the eras 15 | life.set("1000 B.C."); 16 | savedTimes.add(life.saveToMemento()); 17 | life.set("1000 A.D."); 18 | savedTimes.add(life.saveToMemento()); 19 | life.set("2000 A.D."); 20 | savedTimes.add(life.saveToMemento()); 21 | life.set("4000 A.D."); 22 | 23 | life.restoreFromMemento(savedTimes.get(0)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/memento/pattern/Caretaker.java: -------------------------------------------------------------------------------- 1 | package memento.pattern; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Caretaker { 7 | 8 | private List savedStates = new ArrayList(); 9 | 10 | public void addMemento(Memento m) { 11 | savedStates.add(m); 12 | } 13 | 14 | public Memento getMemento(int index) { 15 | return savedStates.get(index); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/memento/pattern/Memento.java: -------------------------------------------------------------------------------- 1 | package memento.pattern; 2 | 3 | public class Memento { 4 | 5 | private String state; 6 | 7 | public Memento(String stateToSave){ 8 | state = stateToSave; 9 | } 10 | 11 | public String getSavedState(){ 12 | return state; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/memento/pattern/MementoTest.java: -------------------------------------------------------------------------------- 1 | package memento.pattern; 2 | 3 | public class MementoTest { 4 | 5 | public static void main(String[] args) { 6 | Caretaker caretaker = new Caretaker(); 7 | 8 | Originator originator = new Originator(); 9 | originator.set("State1"); 10 | originator.set("State2"); 11 | caretaker.addMemento( originator.saveToMemento() ); 12 | originator.set("State3"); 13 | caretaker.addMemento( originator.saveToMemento() ); 14 | originator.set("State4"); 15 | 16 | originator.restoreFromMemento( caretaker.getMemento(1) ); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/memento/pattern/Originator.java: -------------------------------------------------------------------------------- 1 | package memento.pattern; 2 | 3 | public class Originator { 4 | 5 | private String state; 6 | 7 | public void set(String state) { 8 | System.out.println("Originator: Setting state to "+state); 9 | this.state = state; 10 | } 11 | 12 | public Memento saveToMemento(){ 13 | System.out.println("Originator: Saving to Memento."); 14 | return new Memento(state); 15 | } 16 | 17 | public void restoreFromMemento(Memento m) { 18 | state = m.getSavedState(); 19 | System.out.println("Originator: State after restoring from Memento: "+state); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/objectpool/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package objectpool.pattern; 2 | 3 | public class Client implements Runnable { 4 | 5 | private ObjectPool pool; 6 | private int threadNo; 7 | 8 | public Client(ObjectPool pool, int threadNo){ 9 | this.pool = pool; 10 | this.threadNo = threadNo; 11 | } 12 | 13 | public void run() { 14 | // get an object from the pool 15 | HeavyObject heavyObject = pool.borrowObject(); 16 | System.out.println("Thread " + threadNo + ": Object with process no. " + heavyObject.getObjectNo() + " was borrowed"); 17 | 18 | try { 19 | heavyObject.doStuff(); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | 24 | // return ExportingProcess instance back to the pool 25 | pool.returnObject(heavyObject); 26 | 27 | System.out.println("Thread " + threadNo +": Object with process no. " + heavyObject.getObjectNo() + " was returned"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/objectpool/pattern/HeavyObject.java: -------------------------------------------------------------------------------- 1 | package objectpool.pattern; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class HeavyObject { 6 | 7 | private long objectNo; 8 | 9 | public HeavyObject(long objectNo) { 10 | this.objectNo = objectNo; 11 | 12 | // do some expensive calls / tasks here in future 13 | // ......... 14 | 15 | System.out.println("Object with no. " + objectNo + " was created"); 16 | } 17 | 18 | public long getObjectNo() { 19 | return objectNo; 20 | } 21 | 22 | public void doStuff() throws InterruptedException { 23 | //TimeUnit.SECONDS.sleep(1); 24 | System.out.println("Object with no. " + objectNo + " is doing something"); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/objectpool/pattern/ObjectPool.java: -------------------------------------------------------------------------------- 1 | package objectpool.pattern; 2 | 3 | import java.util.concurrent.ConcurrentLinkedQueue; 4 | 5 | abstract class ObjectPool { 6 | 7 | private ConcurrentLinkedQueue pool; 8 | 9 | public ObjectPool(final int minObjects) { 10 | pool = new ConcurrentLinkedQueue(); 11 | for (int i = 0; i < minObjects; i++) { 12 | pool.add(createObject()); 13 | } 14 | } 15 | 16 | protected abstract T createObject(); 17 | 18 | public T borrowObject() { 19 | T object; 20 | if ((object = pool.poll()) == null) { 21 | object = createObject(); 22 | } 23 | return object; 24 | } 25 | 26 | public void returnObject(T object) { 27 | if (object == null) { 28 | return; 29 | } 30 | this.pool.offer(object); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/objectpool/pattern/ObjectPoolTest.java: -------------------------------------------------------------------------------- 1 | package objectpool.pattern; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.TimeUnit; 6 | import java.util.concurrent.atomic.AtomicLong; 7 | 8 | public class ObjectPoolTest { 9 | 10 | private ObjectPool pool; 11 | private AtomicLong processNo=new AtomicLong(0); 12 | 13 | public static void main(String args[]) { 14 | ObjectPoolTest op=new ObjectPoolTest(); 15 | op.setUp(); 16 | op.testObjectPool(); 17 | } 18 | 19 | public void setUp() { 20 | // Create a pool of objects of type HeavyObject. 21 | pool = new ObjectPool(4){ 22 | protected HeavyObject createObject() { 23 | // create a test object which takes some time for creation 24 | return new HeavyObject( processNo.incrementAndGet() ); 25 | } 26 | }; 27 | } 28 | 29 | public void testObjectPool() { 30 | ExecutorService executor = Executors.newFixedThreadPool(8); 31 | 32 | // execute 8 tasks in separate threads 33 | executor.execute(new Client(pool, 1)); 34 | executor.execute(new Client(pool, 2)); 35 | executor.execute(new Client(pool, 3)); 36 | executor.execute(new Client(pool, 4)); 37 | executor.execute(new Client(pool, 5)); 38 | executor.execute(new Client(pool, 6)); 39 | executor.execute(new Client(pool, 7)); 40 | executor.execute(new Client(pool, 8)); 41 | 42 | executor.shutdown(); 43 | try { 44 | executor.awaitTermination(30, TimeUnit.SECONDS); 45 | } catch (InterruptedException e){ 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/observer/examples/auction/AuctionTestDriven.java: -------------------------------------------------------------------------------- 1 | package observer.examples.auction; 2 | 3 | import observer.pattern.Event; 4 | import observer.pattern.Observer; 5 | import observer.pattern.Subject; 6 | 7 | /** 8 | * Created by luisburgos on 15/07/15. 9 | */ 10 | public class AuctionTestDriven { 11 | 12 | public static void main(String[] args) { 13 | 14 | Subject theAuctioneer = new Auctioneer(); 15 | 16 | Observer bidderOne = new Bidder(); 17 | Observer bidderTwo = new Bidder(); 18 | Observer bidderThree = new Bidder(); 19 | 20 | theAuctioneer.attach(0, bidderOne); 21 | theAuctioneer.attach(0, bidderTwo); 22 | theAuctioneer.attach(0, bidderThree); 23 | 24 | theAuctioneer.attach(1, bidderThree); 25 | 26 | Event highBid = new Event(0, "HIGH BID"); 27 | Event lowBid = new Event(1, "LOW BID"); 28 | 29 | theAuctioneer.notifyObserver(0, highBid); 30 | theAuctioneer.notifyObserver(1, lowBid); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/observer/examples/auction/Auctioneer.java: -------------------------------------------------------------------------------- 1 | package observer.examples.auction; 2 | 3 | import observer.pattern.Event; 4 | import observer.pattern.Observer; 5 | import observer.pattern.Subject; 6 | 7 | import java.util.HashMap; 8 | import java.util.Iterator; 9 | import java.util.LinkedList; 10 | 11 | /** 12 | * Created by luisburgos on 15/07/15. 13 | */ 14 | public class Auctioneer extends Subject{ 15 | 16 | private final HashMap> observers; 17 | 18 | public Auctioneer(){ 19 | observers = new HashMap(); 20 | } 21 | 22 | private LinkedList getList(int type) { 23 | if (!observers.containsKey(type)) { 24 | observers.put(type, new LinkedList()); 25 | } 26 | return observers.get(type); 27 | } 28 | 29 | @Override 30 | public void attach(int eventTpye, Observer newObserver) { 31 | getList(eventTpye).add(newObserver); 32 | } 33 | 34 | @Override 35 | public void detach(int eventTpye, Observer observer) { 36 | getList(eventTpye).remove(observer); 37 | } 38 | 39 | @Override 40 | public void notifyObserver(int eventTpye, Event event) { 41 | if (observers.containsKey(eventTpye)){ 42 | Iterator iterator = observers.get(eventTpye).iterator(); 43 | while(iterator.hasNext()){ 44 | iterator.next().update(event); 45 | } 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/observer/examples/auction/Bidder.java: -------------------------------------------------------------------------------- 1 | package observer.examples.auction; 2 | 3 | import observer.pattern.Event; 4 | import observer.pattern.Observer; 5 | 6 | /** 7 | * Created by luisburgos on 15/07/15. 8 | */ 9 | public class Bidder implements Observer { 10 | 11 | private static int ID = 0; 12 | 13 | @Override 14 | public void update(Event event) { 15 | System.out.println( 16 | "ID: " + (++ID) + 17 | ", Updating event type: " + event.getType() + 18 | ", Event description: " + event.getDescription()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/observer/pattern/ConcreteObserver.java: -------------------------------------------------------------------------------- 1 | package observer.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class ConcreteObserver implements Observer { 7 | 8 | private static int ID = 0; 9 | 10 | @Override 11 | public void update(Event event) { 12 | System.out.println( 13 | "ID: " + (++ID) + 14 | ", Updating event type: " + event.getType() + 15 | ", Event description: " + event.getDescription()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/observer/pattern/ConcreteSubject.java: -------------------------------------------------------------------------------- 1 | package observer.pattern; 2 | 3 | import java.util.HashMap; 4 | import java.util.Iterator; 5 | import java.util.LinkedList; 6 | 7 | /** 8 | * Created by luisburgos on 15/07/15. 9 | */ 10 | public class ConcreteSubject extends Subject { 11 | 12 | private final HashMap> observers; 13 | 14 | public ConcreteSubject(){ 15 | observers = new HashMap(); 16 | } 17 | 18 | private LinkedList getList(int type) { 19 | if (!observers.containsKey(type)) { 20 | observers.put(type, new LinkedList()); 21 | } 22 | return observers.get(type); 23 | } 24 | 25 | @Override 26 | public void attach(int eventTpye, Observer newObserver) { 27 | getList(eventTpye).add(newObserver); 28 | } 29 | 30 | @Override 31 | public void detach(int eventTpye, Observer observer) { 32 | getList(eventTpye).remove(observer); 33 | } 34 | 35 | @Override 36 | public void notifyObserver(int eventTpye, Event event) { 37 | if (observers.containsKey(eventTpye)){ 38 | Iterator iterator = observers.get(eventTpye).iterator(); 39 | while(iterator.hasNext()){ 40 | iterator.next().update(event); 41 | } 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/observer/pattern/Event.java: -------------------------------------------------------------------------------- 1 | package observer.pattern; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | /** 8 | * Created by luisburgos on 15/07/15. 9 | */ 10 | public class Event { 11 | 12 | private int type; 13 | private String description; 14 | private Date date; 15 | 16 | public Event(){} 17 | 18 | public Event(int type, String description){ 19 | this.setType(type); 20 | this.setDescription(description); 21 | this.date = new Date(); 22 | } 23 | 24 | public int getType() { 25 | return type; 26 | } 27 | 28 | public void setType(int type) { 29 | this.type = type; 30 | } 31 | 32 | public String getDescription() { 33 | return description; 34 | } 35 | 36 | public void setDescription(String description) { 37 | this.description = description; 38 | } 39 | 40 | public String getDate() { 41 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 42 | return dateFormat.format(date); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/observer/pattern/Observer.java: -------------------------------------------------------------------------------- 1 | package observer.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public interface Observer { 7 | public void update(Event event); 8 | } 9 | -------------------------------------------------------------------------------- /src/observer/pattern/Subject.java: -------------------------------------------------------------------------------- 1 | package observer.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public abstract class Subject { 7 | 8 | public abstract void attach(int eventTpye, Observer observer); 9 | public abstract void detach(int eventTpye, Observer observer); 10 | public abstract void notifyObserver(int eventTpye, Event event); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/observer/pattern/Test.java: -------------------------------------------------------------------------------- 1 | package observer.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 15/07/15. 5 | */ 6 | public class Test { 7 | 8 | public static void main(String[] args) { 9 | 10 | Subject concreteSubject = new ConcreteSubject(); 11 | 12 | Observer concreteObserverOne = new ConcreteObserver(); 13 | Observer concreteObserverTwo = new ConcreteObserver(); 14 | Observer concreteObserverThree = new ConcreteObserver(); 15 | 16 | concreteSubject.attach(0, concreteObserverOne); 17 | concreteSubject.attach(0, concreteObserverTwo); 18 | concreteSubject.attach(1, concreteObserverOne); 19 | concreteSubject.attach(1, concreteObserverThree); 20 | concreteSubject.attach(2, concreteObserverTwo); 21 | concreteSubject.attach(3, concreteObserverThree); 22 | 23 | Event mainEvent = new Event(0, "Main event: "); 24 | Event firstEvent = new Event(1, "First event: "); 25 | Event secondEvent = new Event(2, "Second event: "); 26 | Event thirdEvent = new Event(3, "Third event: "); 27 | 28 | concreteSubject.notifyObserver(0, mainEvent); 29 | concreteSubject.notifyObserver(1, firstEvent); 30 | concreteSubject.notifyObserver(2, secondEvent); 31 | concreteSubject.notifyObserver(3, thirdEvent); 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/prototype/examples/animals/Animal.java: -------------------------------------------------------------------------------- 1 | package prototype.examples.animals; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public interface Animal extends Cloneable{ 7 | public Animal clone(); 8 | } 9 | -------------------------------------------------------------------------------- /src/prototype/examples/animals/AnimalCloneFactory.java: -------------------------------------------------------------------------------- 1 | package prototype.examples.animals; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class AnimalCloneFactory { 7 | 8 | public Animal getClone(Animal animalSample) { 9 | return animalSample.clone(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/prototype/examples/animals/AnimalPrototypeTest.java: -------------------------------------------------------------------------------- 1 | package prototype.examples.animals; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class AnimalPrototypeTest { 7 | 8 | public static void main(String[] args) { 9 | 10 | AnimalCloneFactory factory = new AnimalCloneFactory(); 11 | Animal animal; 12 | Animal clonedAnimal; 13 | 14 | System.out.println("Turn of the dogs..."); 15 | 16 | animal = new Dog(); 17 | clonedAnimal = (Dog) factory.getClone(animal); 18 | System.out.println(animal + " with ID: " + System.identityHashCode(System.identityHashCode(animal))); 19 | System.out.println(clonedAnimal + " with ID: " + System.identityHashCode(System.identityHashCode(clonedAnimal))); 20 | 21 | System.out.println("Turn of the cats..."); 22 | 23 | animal = new Cat(); 24 | clonedAnimal = (Cat) factory.getClone(animal); 25 | System.out.println(animal + " with ID: " + System.identityHashCode(System.identityHashCode(animal))); 26 | System.out.println(clonedAnimal + " with ID: " + System.identityHashCode(System.identityHashCode(clonedAnimal))); 27 | 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/prototype/examples/animals/Cat.java: -------------------------------------------------------------------------------- 1 | package prototype.examples.animals; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class Cat implements Animal { 7 | @Override 8 | public Animal clone() { 9 | Cat catClone = null; 10 | 11 | try { 12 | catClone = (Cat) super.clone(); 13 | } 14 | catch (CloneNotSupportedException e) { 15 | e.printStackTrace(); 16 | } 17 | 18 | return catClone; 19 | } 20 | 21 | public String toString(){ 22 | return "This is a Cat"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/prototype/examples/animals/Dog.java: -------------------------------------------------------------------------------- 1 | package prototype.examples.animals; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class Dog implements Animal { 7 | @Override 8 | public Animal clone() { 9 | Dog dogClone = null; 10 | 11 | try { 12 | dogClone = (Dog) super.clone(); 13 | } 14 | catch (CloneNotSupportedException e) { 15 | e.printStackTrace(); 16 | } 17 | 18 | return dogClone; 19 | } 20 | 21 | public String toString(){ 22 | return "This is a Dog"; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/prototype/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package prototype.pattern; 2 | 3 | 4 | /** 5 | * Created by luisburgos on 23/07/15. 6 | */ 7 | public class Client { 8 | 9 | public static void main(String[] args) { 10 | 11 | PrototypeFactory factory = new PrototypeFactory(); 12 | 13 | Prototype object = new ConcretePrototypeOne(); 14 | ConcretePrototypeOne clonedObject = (ConcretePrototypeOne) factory.getClone(object); 15 | 16 | System.out.println(object); 17 | System.out.println(clonedObject); 18 | System.out.println("Object: " + System.identityHashCode(System.identityHashCode(object))); 19 | System.out.println("Cloned Object HashCode: " + System.identityHashCode(System.identityHashCode(clonedObject))); 20 | 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/prototype/pattern/ConcretePrototypeOne.java: -------------------------------------------------------------------------------- 1 | package prototype.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class ConcretePrototypeOne implements Prototype { 7 | @Override 8 | public ConcretePrototypeOne clone() { 9 | 10 | ConcretePrototypeOne copyObject = null; 11 | 12 | try{ 13 | copyObject = (ConcretePrototypeOne)super.clone(); 14 | }catch(CloneNotSupportedException ex){ 15 | ex.printStackTrace(); 16 | } 17 | 18 | return copyObject; 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return "Concrete Prototype One"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/prototype/pattern/ConcretePrototypeTwo.java: -------------------------------------------------------------------------------- 1 | package prototype.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class ConcretePrototypeTwo implements Prototype { 7 | @Override 8 | public Prototype clone() { 9 | 10 | ConcretePrototypeTwo copyObject = null; 11 | 12 | try{ 13 | copyObject = (ConcretePrototypeTwo)super.clone(); 14 | }catch(CloneNotSupportedException ex){ 15 | ex.printStackTrace(); 16 | } 17 | 18 | return copyObject; 19 | } 20 | 21 | @Override 22 | public String toString() { 23 | return "Concrete Prototype Two"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/prototype/pattern/Prototype.java: -------------------------------------------------------------------------------- 1 | package prototype.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public interface Prototype extends Cloneable { 7 | public Prototype clone(); 8 | } 9 | -------------------------------------------------------------------------------- /src/prototype/pattern/PrototypeFactory.java: -------------------------------------------------------------------------------- 1 | package prototype.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 23/07/15. 5 | */ 6 | public class PrototypeFactory { 7 | 8 | public Prototype getClone(Prototype proto){ 9 | return proto.clone(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/proxy/examples/atm/ATMClient.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.atm; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public class ATMClient { 7 | 8 | public static void main(String[] args) { 9 | 10 | GetATMData realAtmMachine = new ATMMachine(1000); 11 | GetATMData atmProxy = new ATMProxy(realAtmMachine); 12 | 13 | System.out.println("ATM Machine, cash available: " + atmProxy.getCashInMachine()); 14 | 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/proxy/examples/atm/ATMMachine.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.atm; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public class ATMMachine implements GetATMData { 7 | 8 | private int cashInMachine; 9 | 10 | public ATMMachine(int cashInMachine){ 11 | this.cashInMachine = cashInMachine; 12 | } 13 | @Override 14 | public int getCashInMachine() { 15 | return cashInMachine; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/proxy/examples/atm/ATMProxy.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.atm; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public class ATMProxy implements GetATMData { 7 | 8 | private GetATMData atmMachine; 9 | 10 | public ATMProxy(GetATMData atmMachine){ 11 | this.atmMachine = atmMachine; 12 | } 13 | 14 | @Override 15 | public int getCashInMachine() { 16 | return atmMachine.getCashInMachine(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/proxy/examples/atm/GetATMData.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.atm; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public interface GetATMData { 7 | public int getCashInMachine(); 8 | } 9 | -------------------------------------------------------------------------------- /src/proxy/examples/images/ClientImage.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.images; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public class ClientImage { 7 | 8 | public static void main(String[] args) { 9 | 10 | Image image = new ProxyImage("img_10.jpg"); 11 | 12 | //image will be loaded from disk 13 | image.display(); 14 | System.out.println(""); 15 | 16 | //image will NOT be loaded from disk 17 | image.display(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/proxy/examples/images/Image.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.images; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public interface Image { 7 | public void display(); 8 | } 9 | -------------------------------------------------------------------------------- /src/proxy/examples/images/ProxyImage.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.images; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public class ProxyImage implements Image { 7 | 8 | private RealImage realImage; 9 | private String imageFileName; 10 | 11 | public ProxyImage(String fileName){ 12 | this.imageFileName = fileName; 13 | } 14 | 15 | @Override 16 | public void display() { 17 | if(realImage == null){ 18 | realImage = new RealImage(imageFileName); 19 | } 20 | realImage.display(); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/proxy/examples/images/RealImage.java: -------------------------------------------------------------------------------- 1 | package proxy.examples.images; 2 | 3 | /** 4 | * Created by luisburgos on 21/09/15. 5 | */ 6 | public class RealImage implements Image { 7 | 8 | private String imageFileName; 9 | 10 | public RealImage(String imageFileName){ 11 | this.imageFileName = imageFileName; 12 | loadFromDisk(imageFileName); 13 | } 14 | 15 | @Override 16 | public void display() { 17 | System.out.println("Displaying " + imageFileName); 18 | } 19 | 20 | private void loadFromDisk(String imageFileName){ 21 | System.out.println("Loading " + imageFileName); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/proxy/pattern/Client.java: -------------------------------------------------------------------------------- 1 | package proxy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 20/09/15. 5 | */ 6 | public class Client { 7 | 8 | public static void main(String[] args) { 9 | 10 | Subject proxyToRealSubject = new Proxy(new RealSubject()); 11 | proxyToRealSubject.doService(); 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/proxy/pattern/Proxy.java: -------------------------------------------------------------------------------- 1 | package proxy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 20/09/15. 5 | */ 6 | public class Proxy implements Subject { 7 | 8 | private Subject wrapee; 9 | 10 | public Proxy(Subject wrapee){ 11 | this.wrapee = wrapee; 12 | } 13 | 14 | @Override 15 | public void doService() { 16 | anotherFunctionality(); 17 | if(wrapee == null){ 18 | wrapee = new RealSubject(); //Just for this pattern example 19 | } 20 | wrapee.doService(); 21 | } 22 | 23 | private void anotherFunctionality() { 24 | System.out.println("Doing another functionality from Proxy..."); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/proxy/pattern/RealSubject.java: -------------------------------------------------------------------------------- 1 | package proxy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 20/09/15. 5 | */ 6 | public class RealSubject implements Subject{ 7 | @Override 8 | public void doService() { 9 | System.out.println("Real Subject doing service..."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/proxy/pattern/Subject.java: -------------------------------------------------------------------------------- 1 | package proxy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 20/09/15. 5 | */ 6 | public interface Subject { 7 | public void doService(); 8 | } 9 | -------------------------------------------------------------------------------- /src/singleton/examples/government/Government.java: -------------------------------------------------------------------------------- 1 | package singleton.examples.government; 2 | 3 | /** 4 | * Created by luisburgos on 19/07/15. 5 | */ 6 | public class Government { 7 | 8 | static Government government; 9 | 10 | private Government () { } 11 | 12 | public synchronized static Government getGovernment(){ 13 | if(government == null){ 14 | government = new Government(); 15 | } 16 | return government; 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/singleton/pattern/Singleton.java: -------------------------------------------------------------------------------- 1 | package singleton.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 19/07/15. 5 | */ 6 | public class Singleton { 7 | 8 | static Singleton instance; 9 | 10 | private Singleton () { 11 | 12 | } 13 | 14 | /** 15 | * The instance gets created only when it is called for first time. 16 | * Lazy-loading. 17 | * This way singleton is thread-safe 18 | * @return 19 | */ 20 | public synchronized static Singleton getInstance(){ 21 | if(instance == null){ 22 | instance = new Singleton(); 23 | } 24 | return instance; 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/singleton/pattern/Test.java: -------------------------------------------------------------------------------- 1 | package singleton.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 19/07/15. 5 | */ 6 | public class Test { 7 | 8 | public static void main(String[] args) { 9 | 10 | Singleton singletonOne = Singleton.getInstance(); 11 | Singleton singletonTwo = Singleton.getInstance(); 12 | 13 | if(singletonOne == singletonTwo){ 14 | System.out.println("Objects are the same instance"); 15 | System.out.println(" Singleton one hash code: " + System.identityHashCode(singletonOne)); 16 | System.out.println(" Singleton two hash code: " + System.identityHashCode(singletonTwo)); 17 | } 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/state/examples/mobilealerts/AlertStateContext.java: -------------------------------------------------------------------------------- 1 | package state.examples.mobilealerts; 2 | 3 | public class AlertStateContext { 4 | private MobileAlertState currentState; 5 | 6 | public AlertStateContext(){ 7 | currentState = new Vibration(); 8 | } 9 | 10 | public void setState(MobileAlertState state){ 11 | currentState = state; 12 | } 13 | 14 | public void alert() { 15 | currentState.alert(this); 16 | } 17 | } -------------------------------------------------------------------------------- /src/state/examples/mobilealerts/MobileAlertState.java: -------------------------------------------------------------------------------- 1 | package state.examples.mobilealerts; 2 | 3 | public interface MobileAlertState { 4 | void alert(AlertStateContext ctx); 5 | } 6 | -------------------------------------------------------------------------------- /src/state/examples/mobilealerts/Ring.java: -------------------------------------------------------------------------------- 1 | package state.examples.mobilealerts; 2 | 3 | public class Ring implements MobileAlertState { 4 | @Override 5 | public void alert(AlertStateContext ctx) { 6 | System.out.println("ringing..."); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/state/examples/mobilealerts/Silent.java: -------------------------------------------------------------------------------- 1 | package state.examples.mobilealerts; 2 | 3 | public class Silent implements MobileAlertState { 4 | @Override 5 | public void alert(AlertStateContext ctx) { 6 | System.out.println("silent..."); 7 | } 8 | } -------------------------------------------------------------------------------- /src/state/examples/mobilealerts/StateClient.java: -------------------------------------------------------------------------------- 1 | package state.examples.mobilealerts; 2 | 3 | public class StateClient { 4 | 5 | public static void main(String[] args) { 6 | AlertStateContext stateContext = new AlertStateContext(); 7 | stateContext.alert(); 8 | stateContext.alert(); 9 | stateContext.setState(new Silent()); 10 | stateContext.alert(); 11 | stateContext.alert(); 12 | stateContext.setState(new Ring()); 13 | stateContext.alert(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/state/examples/mobilealerts/Vibration.java: -------------------------------------------------------------------------------- 1 | package state.examples.mobilealerts; 2 | 3 | public class Vibration implements MobileAlertState { 4 | @Override 5 | public void alert(AlertStateContext ctx) { 6 | System.out.println("vibration..."); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/state/pattern/Context.java: -------------------------------------------------------------------------------- 1 | package state.pattern; 2 | 3 | public class Context { 4 | private State state; 5 | 6 | public void setState( State state ){ 7 | this.state = state; 8 | } 9 | 10 | public State getState(){ 11 | return state; 12 | } 13 | 14 | public void request() { 15 | state.handle(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/state/pattern/State.java: -------------------------------------------------------------------------------- 1 | package state.pattern; 2 | 3 | public interface State { 4 | void handle(); 5 | } 6 | -------------------------------------------------------------------------------- /src/state/pattern/StateA.java: -------------------------------------------------------------------------------- 1 | package state.pattern; 2 | 3 | public class StateA implements State { 4 | 5 | public void handle() { 6 | System.out.println("Doing StateA stuffs"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/state/pattern/StateB.java: -------------------------------------------------------------------------------- 1 | package state.pattern; 2 | 3 | public class StateB implements State { 4 | 5 | public void handle() { 6 | System.out.println("Doing StateB stuffs"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/strategy/examples/robot/AgressiveBehavior.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.robot; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class AgressiveBehavior implements RobotBehavior { 7 | @Override 8 | public int moveCommand() { 9 | return 1; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return "Agressive Behaviour: if find another robot attack it"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/strategy/examples/robot/DefensiveBehavior.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.robot; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class DefensiveBehavior implements RobotBehavior { 7 | @Override 8 | public int moveCommand() { 9 | return -1; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return "Defensive Behaviour: if find another robot run from it"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/strategy/examples/robot/NormalBehavior.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.robot; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class NormalBehavior implements RobotBehavior { 7 | @Override 8 | public int moveCommand() { 9 | return 0; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return "Normal Behaviour: if find another robot ignore it"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/strategy/examples/robot/Robot.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.robot; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class Robot { 7 | 8 | private RobotBehavior behavior; 9 | private String name; 10 | 11 | public Robot(){} 12 | 13 | public RobotBehavior getBehavior() { 14 | return behavior; 15 | } 16 | 17 | public void setBehavior(RobotBehavior behavior) { 18 | this.behavior = behavior; 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | 29 | public void move(){ 30 | int command = behavior.moveCommand(); 31 | System.out.println("Move command: " + command + ". " + behavior.toString()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/strategy/examples/robot/RobotBehavior.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.robot; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public interface RobotBehavior { 7 | public int moveCommand(); 8 | } 9 | -------------------------------------------------------------------------------- /src/strategy/examples/robot/RobotTestDrive.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.robot; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class RobotTestDrive { 7 | 8 | public static void main(String[] args) { 9 | 10 | Robot roboto = new Robot(); 11 | roboto.setName("Mr. Roboto"); 12 | roboto.setBehavior(new AgressiveBehavior()); 13 | 14 | roboto.move(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/strategy/examples/transportation/CityBus.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.transportation; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class CityBus implements TransportationMode { 7 | 8 | @Override 9 | public String travel() { 10 | return "Traveling to Airport in: CityBus"; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/strategy/examples/transportation/PersonalCar.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.transportation; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class PersonalCar implements TransportationMode { 7 | 8 | @Override 9 | public String travel() { 10 | return "Traveling to Airport in: PersonalCar"; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/strategy/examples/transportation/Taxi.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.transportation; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class Taxi implements TransportationMode { 7 | 8 | @Override 9 | public String travel() { 10 | return "Traveling to Airport in: Taxi"; 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/strategy/examples/transportation/TransportationMode.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.transportation; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public interface TransportationMode { 7 | public String travel(); 8 | } 9 | -------------------------------------------------------------------------------- /src/strategy/examples/transportation/TransportationModeTestDrive.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.transportation; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class TransportationModeTestDrive { 7 | 8 | public static void main(String[] args) { 9 | 10 | Traveler johnTraveler = new Traveler("John"); 11 | Traveler lucyTraveler = new Traveler("Lucy"); 12 | Traveler rickTraveler = new Traveler("Rick"); 13 | 14 | johnTraveler.setTransportationMode(new CityBus()); 15 | lucyTraveler.setTransportationMode(new PersonalCar()); 16 | rickTraveler.setTransportationMode(new Taxi()); 17 | 18 | johnTraveler.travelToAirport(); 19 | lucyTraveler.travelToAirport(); 20 | rickTraveler.travelToAirport(); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/strategy/examples/transportation/Traveler.java: -------------------------------------------------------------------------------- 1 | package strategy.examples.transportation; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class Traveler { 7 | 8 | private String name; 9 | private TransportationMode transportationMode; 10 | 11 | public Traveler(){} 12 | 13 | public Traveler(String name){ 14 | this.setName(name); 15 | } 16 | 17 | public void setTransportationMode(TransportationMode transportationMode){ 18 | this.transportationMode = transportationMode; 19 | } 20 | 21 | public TransportationMode getTransportationMode(){ 22 | return transportationMode; 23 | } 24 | 25 | public void travelToAirport(){ 26 | System.out.println(this.toString() + getTransportationMode().travel()); 27 | } 28 | 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "I am " + getName() + ". "; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/strategy/pattern/ConcreteStrategyOne.java: -------------------------------------------------------------------------------- 1 | package strategy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class ConcreteStrategyOne implements Strategy { 7 | @Override 8 | public String doSomething() { 9 | return "ConcreteStrategyOne"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/strategy/pattern/ConcreteStrategyTwo.java: -------------------------------------------------------------------------------- 1 | package strategy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class ConcreteStrategyTwo implements Strategy { 7 | @Override 8 | public String doSomething() { 9 | return "Concrete Strategy Two"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/strategy/pattern/Context.java: -------------------------------------------------------------------------------- 1 | package strategy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public class Context { 7 | 8 | private Strategy strategy; 9 | 10 | public Context(){} 11 | 12 | public void setStrategy(Strategy behavior) { 13 | this.strategy = behavior; 14 | } 15 | 16 | public Strategy getStrategy() { 17 | return strategy; 18 | } 19 | 20 | public void executeStrategy(){ 21 | System.out.println(strategy.doSomething()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/strategy/pattern/Strategy.java: -------------------------------------------------------------------------------- 1 | package strategy.pattern; 2 | 3 | /** 4 | * Created by luisburgos on 12/07/15. 5 | */ 6 | public interface Strategy { 7 | public String doSomething(); 8 | } 9 | -------------------------------------------------------------------------------- /src/template/examples/ordermanaging/Client.java: -------------------------------------------------------------------------------- 1 | package template.examples.ordermanaging; 2 | 3 | public class Client { 4 | 5 | public static void main(String[] args) { 6 | OrderProcessTemplate netOrder = new NetOrder(); 7 | netOrder.processOrder(true); 8 | System.out.println(); 9 | OrderProcessTemplate storeOrder = new StoreOrder(); 10 | storeOrder.processOrder(true); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/template/examples/ordermanaging/NetOrder.java: -------------------------------------------------------------------------------- 1 | package template.examples.ordermanaging; 2 | 3 | public class NetOrder extends OrderProcessTemplate { 4 | @Override 5 | public void doSelect() { 6 | System.out.println("Item added to online shopping cart"); 7 | System.out.println("Get gift wrap preference"); 8 | System.out.println("Get delivery address."); 9 | } 10 | 11 | @Override 12 | public void doPayment() { 13 | System.out.println("Online Payment through Netbanking, card or Paytm"); 14 | } 15 | 16 | @Override 17 | public void doDelivery() { 18 | System.out.println("Ship the item through post to delivery address"); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/template/examples/ordermanaging/OrderProcessTemplate.java: -------------------------------------------------------------------------------- 1 | package template.examples.ordermanaging; 2 | 3 | public abstract class OrderProcessTemplate { 4 | public boolean isGift; 5 | 6 | public abstract void doSelect(); 7 | 8 | public abstract void doPayment(); 9 | 10 | public abstract void doDelivery(); 11 | 12 | public final void processOrder(boolean isGift) { 13 | doSelect(); 14 | doPayment(); 15 | if (isGift) { 16 | giftWrap(); 17 | } 18 | doDelivery(); 19 | } 20 | 21 | public final void giftWrap() { 22 | try { 23 | System.out.println("Gift wrap successfull"); 24 | } 25 | catch (Exception e) { 26 | System.out.println("Gift wrap unsuccessful"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/template/examples/ordermanaging/StoreOrder.java: -------------------------------------------------------------------------------- 1 | package template.examples.ordermanaging; 2 | 3 | public class StoreOrder extends OrderProcessTemplate { 4 | 5 | @Override 6 | public void doSelect() { 7 | System.out.println("Customer chooses the item from shelf."); 8 | } 9 | 10 | @Override 11 | public void doPayment() { 12 | System.out.println("Pays at counter through cash/POS"); 13 | } 14 | 15 | @Override 16 | public void doDelivery() { 17 | System.out.println("Item deliverd to in delivery counter."); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/visitor/examples/airportsecuritycontrol/InternationalPassenger.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.airportsecuritycontrol; 2 | 3 | import java.util.List; 4 | 5 | public class InternationalPassenger implements Passenger{ 6 | private String passport; 7 | private Boolean visa; 8 | private List belongings; 9 | 10 | public InternationalPassenger(String passport, Boolean visa, List belongings) { 11 | this.passport = passport; 12 | this.visa = visa; 13 | this.belongings = belongings; 14 | } 15 | 16 | public String getPassport() { 17 | return passport; 18 | } 19 | 20 | public Boolean getVisa() { 21 | return visa; 22 | } 23 | 24 | public List getBelongings() { 25 | return belongings; 26 | } 27 | 28 | @Override 29 | public boolean accept(PoliceOfficer visitor) { 30 | return visitor.visit(this); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/visitor/examples/airportsecuritycontrol/NationalPassenger.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.airportsecuritycontrol; 2 | 3 | import java.util.List; 4 | 5 | public class NationalPassenger implements Passenger{ 6 | private String identityDocument; 7 | private List belongings; 8 | 9 | public NationalPassenger(String identityDocument, List belongings) { 10 | this.identityDocument = identityDocument; 11 | this.belongings = belongings; 12 | } 13 | 14 | public String getIdentityDocument() { 15 | return identityDocument; 16 | } 17 | 18 | public List getBelongings() { 19 | return belongings; 20 | } 21 | 22 | @Override 23 | public boolean accept(PoliceOfficer visitor) { 24 | return visitor.visit(this); 25 | } 26 | } -------------------------------------------------------------------------------- /src/visitor/examples/airportsecuritycontrol/Passenger.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.airportsecuritycontrol; 2 | 3 | public interface Passenger { 4 | boolean accept(PoliceOfficer visitor); 5 | } 6 | -------------------------------------------------------------------------------- /src/visitor/examples/airportsecuritycontrol/PoliceOfficer.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.airportsecuritycontrol; 2 | 3 | import java.util.List; 4 | 5 | public class PoliceOfficer { 6 | 7 | public boolean visit(NationalPassenger passenger) { 8 | boolean checked=false; 9 | if(checkIdentification(passenger.getIdentityDocument()) && checkBelongings(passenger.getBelongings())) { 10 | checked=true; 11 | } 12 | 13 | return checked; 14 | } 15 | 16 | private boolean checkIdentification(String id) { 17 | return id!=null && !id.equals(""); 18 | } 19 | 20 | private boolean checkBelongings(List belongings) { 21 | return !belongings.contains("Liquids"); 22 | } 23 | 24 | public boolean visit(InternationalPassenger passenger) { 25 | boolean checked=false; 26 | if(checkIdentification(passenger.getPassport()) && checkBelongings(passenger.getBelongings()) && passenger.getVisa()) { 27 | checked=true; 28 | } 29 | return checked; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/visitor/examples/airportsecuritycontrol/SecurityControlClient.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.airportsecuritycontrol; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | public class SecurityControlClient { 7 | 8 | public static void main(String[] args) { 9 | Passenger[] passengers = new Passenger[] {new NationalPassenger("45874005H", Arrays.asList("Coins","Bag","Sun glasses")), 10 | new NationalPassenger(null, Collections.EMPTY_LIST), 11 | new InternationalPassenger("4A4585BC", true, Arrays.asList("Cap","False beard","Gun")), 12 | new InternationalPassenger("11AB8564", false, Arrays.asList("Suitcase","Coat")), 13 | new InternationalPassenger("269LZF74", false, Arrays.asList("Liquids"))}; 14 | 15 | PoliceOfficer officer = new PoliceOfficer(); 16 | 17 | for(Passenger p: passengers) { 18 | if(p.accept(officer)) { 19 | System.out.println("Access granted"); 20 | }else { 21 | System.out.println("Access NOT granted"); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/Client.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public class Client { 4 | 5 | public static void main(String argv[]) { 6 | // Construcción de una expresión (a+5)*(b+1) 7 | Expression expresion = new Mult( new Sum( new Variable("a"), 8 | new Constant(5) ), 9 | new Sum( new Variable("b"), 10 | new Constant(1) )); 11 | 12 | VisitorExpression expr = new VisitorExpression(); 13 | expresion.aceptar(expr); 14 | 15 | // Visualizacion de resultados 16 | System.out.println("Resultado: " + expr.obtenerResultado()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/Constant.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public class Constant extends Expression { 4 | int _valor; 5 | 6 | public Constant(int valor) { 7 | _valor = valor; 8 | } 9 | 10 | public void aceptar(VisitorExpression v) { 11 | v.visitConstant(this); 12 | } 13 | } -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/Expression.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public abstract class Expression { 4 | abstract public void aceptar(VisitorExpression v); 5 | } 6 | -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/Mult.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public class Mult extends OpBinary { 4 | public Mult(Expression izq, Expression der) { 5 | super(izq, der); 6 | } 7 | 8 | public void aceptar(VisitorExpression v) { 9 | v.visitMult(this); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/OpBinary.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public abstract class OpBinary extends Expression { 4 | Expression _izq, _der; 5 | 6 | public OpBinary(Expression izq, Expression der) { 7 | _izq = izq; _der = der; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/Sum.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public class Sum extends OpBinary { 4 | public Sum(Expression izq, Expression der) { 5 | super(izq, der); 6 | } 7 | 8 | public void aceptar(VisitorExpression v) { 9 | v.visitSum(this); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/Variable.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public class Variable extends Expression { 4 | String _variable; 5 | 6 | public Variable(String variable) { 7 | _variable = variable; 8 | } 9 | 10 | public void aceptar(VisitorExpression v) { 11 | v.visitVariable(this); 12 | } 13 | } -------------------------------------------------------------------------------- /src/visitor/examples/arithmetic/VisitorExpression.java: -------------------------------------------------------------------------------- 1 | package visitor.examples.arithmetic; 2 | 3 | public class VisitorExpression { 4 | 5 | private String _resultado; 6 | 7 | public void visitVariable(Variable v) { 8 | _resultado = v._variable; 9 | } 10 | 11 | public void visitConstant(Constant c) { 12 | _resultado = String.valueOf(c._valor); 13 | } 14 | 15 | private void visitOpBinary(OpBinary op, String pOperacion) { 16 | op._izq.aceptar(this); 17 | String pIzq = obtenerResultado(); 18 | 19 | op._der.aceptar(this); 20 | String pDer = obtenerResultado(); 21 | 22 | _resultado = "(" + pIzq + pOperacion + pDer + ")"; 23 | } 24 | 25 | public void visitSum(Sum s) { 26 | visitOpBinary(s, "+"); 27 | } 28 | 29 | public void visitMult(Mult m) { 30 | visitOpBinary(m, "*"); 31 | } 32 | 33 | public String obtenerResultado() { 34 | return _resultado; 35 | } 36 | } --------------------------------------------------------------------------------