├── README.md └── java ├── adapter ├── ducks │ ├── Duck.java │ ├── DuckAdapter.java │ ├── DuckTestDrive.java │ ├── MallardDuck.java │ ├── Turkey.java │ ├── TurkeyAdapter.java │ ├── TurkeyTestDrive.java │ └── WildTurkey.java └── iterenum │ ├── EI.java │ ├── EnumerationIterator.java │ ├── EnumerationIteratorTestDrive.java │ ├── IteratorEnumeration.java │ └── IteratorEnumerationTestDrive.java ├── command ├── party │ ├── CeilingFan.java │ ├── CeilingFanHighCommand.java │ ├── CeilingFanMediumCommand.java │ ├── CeilingFanOffCommand.java │ ├── Command.java │ ├── Hottub.java │ ├── HottubOffCommand.java │ ├── HottubOnCommand.java │ ├── Light.java │ ├── LightOffCommand.java │ ├── LightOnCommand.java │ ├── LightroomLightOffCommand.java │ ├── LivingroomLightOnCommand.java │ ├── MacroCommand.java │ ├── NoCommand.java │ ├── RemoteControl.java │ ├── RemoteLoader.java │ ├── Stereo.java │ ├── StereoOffCommand.java │ ├── StereoOnCommand.java │ ├── StereoOnWithCDCommand.java │ ├── TV.java │ ├── TVOffCommand.java │ └── TVOnCommand.java ├── remote │ ├── CeilingFan.java │ ├── CeilingFanOffCommand.java │ ├── CeilingFanOnCommand.java │ ├── Command.java │ ├── GarageDoor.java │ ├── GarageDoorDownCommand.java │ ├── GarageDoorUpCommand.java │ ├── Hottub.java │ ├── HottubOffCommand.java │ ├── HottubOnCommand.java │ ├── Light.java │ ├── LightOffCommand.java │ ├── LightOnCommand.java │ ├── LivingroomLightOffCommand.java │ ├── LivingroomLightOnCommand.java │ ├── NoCommand.java │ ├── RemoteControl.java │ ├── RemoteLoader.java │ ├── Stereo.java │ ├── StereoOffCommand.java │ ├── StereoOnWithCDCommand.java │ └── TV.java ├── simpleremote │ ├── Command.java │ ├── GarageDoor.java │ ├── GarageDoorOpenCommand.java │ ├── Light.java │ ├── LightOffCommand.java │ ├── LightOnCommand.java │ ├── RemoteControlTest.java │ └── SimpleRemoteControl.java └── undo │ ├── CeilingFan.java │ ├── CeilingFanHighCommand.java │ ├── CeilingFanLowCommand.java │ ├── CeilingFanMediumCommand.java │ ├── CeilingFanOffCommand.java │ ├── Command.java │ ├── DimmerLightOffCommand.java │ ├── DimmerLightOnCommand.java │ ├── Light.java │ ├── LightOffCommand.java │ ├── LightOnCommand.java │ ├── NoCommand.java │ ├── RemoteControlWithUndo.java │ └── RemoteLoader.java ├── composite ├── menu │ ├── Menu.java │ ├── MenuComponent.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ └── Waitress.java └── menuiterator │ ├── CompositeIterator.java │ ├── Menu.java │ ├── MenuComponent.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── NullIterator.java │ └── Waitress.java ├── compound ├── combined │ └── djview │ │ ├── BPMObserver.java │ │ ├── BeatBar.java │ │ ├── BeatController.java │ │ ├── BeatModel.java │ │ ├── BeatModelInterface.java │ │ ├── BeatObserver.java │ │ ├── ControllerInterface.java │ │ ├── DJTestDrive.java │ │ └── DJView.java └── combining │ ├── adapter │ ├── DuckCall.java │ ├── DuckSimulator.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java │ ├── composite │ ├── AbstractDuckFactory.java │ ├── CountingDuckFactory.java │ ├── DuckCall.java │ ├── DuckFactory.java │ ├── DuckSimulator.java │ ├── Flock.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── QuackCounter.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java │ ├── decorator │ ├── DuckCall.java │ ├── DuckSimulator.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── QuackCounter.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java │ ├── ducks │ ├── DuckCall.java │ ├── DuckSimulator.java │ ├── MallardDuck.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java │ ├── factory │ ├── AbstractDuckFactory.java │ ├── CountingDuckFactory.java │ ├── DuckCall.java │ ├── DuckFactory.java │ ├── DuckSimulator.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── QuackCounter.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java │ └── observer │ ├── AbstractDuckFactory.java │ ├── CountingDuckFactory.java │ ├── DuckCall.java │ ├── DuckFactory.java │ ├── DuckSimulator.java │ ├── Flock.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── Observable.java │ ├── Observer.java │ ├── QuackCounter.java │ ├── QuackObservable.java │ ├── Quackable.java │ ├── Quackologist.java │ ├── RedheadDuck.java │ └── RubberDuck.java ├── decorator ├── io │ ├── InputTest.java │ └── LowerCaseInputStream.java └── starbuzz │ ├── Beverage.java │ ├── CondimentDecorator.java │ ├── DarkRoast.java │ ├── Decaf.java │ ├── Espresso.java │ ├── HouseBlend.java │ ├── Mocha.java │ ├── Soy.java │ ├── StarbuzzCoffee.java │ ├── SteamedMilk.java │ └── Whip.java ├── facade └── hometheater │ ├── Amplifier.java │ ├── CdPlayer.java │ ├── DvdPlayer.java │ ├── HomeTheaterFacade.java │ ├── HomeTheaterTestDrive.java │ ├── PopcornPopper.java │ ├── Projector.java │ ├── Screen.java │ ├── TheaterLights.java │ └── Tuner.java ├── factory ├── pizzaaf │ ├── BlackOlives.java │ ├── Cheese.java │ ├── CheesePizza.java │ ├── ChicagoPizzaIngredientFactory.java │ ├── ChicagoPizzaStore.java │ ├── ClamPizza.java │ ├── Clams.java │ ├── Dough.java │ ├── Eggplant.java │ ├── FreshClams.java │ ├── FrozenClams.java │ ├── Garlic.java │ ├── MarinaraSauce.java │ ├── MozzarellaCheese.java │ ├── Mushroom.java │ ├── NYPizzaIngredientFactory.java │ ├── NYPizzaStore.java │ ├── Onion.java │ ├── ParmesanCheese.java │ ├── Pepperoni.java │ ├── PepperoniPizza.java │ ├── Pizza.java │ ├── PizzaIngredientFactory.java │ ├── PizzaStore.java │ ├── PizzaTestDrive.java │ ├── PlumTomatoSauce.java │ ├── RedPepper.java │ ├── ReggianoCheese.java │ ├── Sauce.java │ ├── SlicedPepperoni.java │ ├── Spinach.java │ ├── ThickCrustDough.java │ ├── ThinCrustDough.java │ ├── VeggiePizza.java │ └── Veggies.java └── pizzafm │ ├── ChicagoPizzaStore.java │ ├── ChicagoStyleCheesePizza.java │ ├── ChicagoStyleClamPizza.java │ ├── ChicagoStylePepperoniPizza.java │ ├── ChicagoStyleVeggiePizza.java │ ├── NYPizzaStore.java │ ├── NYStyleCheesePizza.java │ ├── NYStyleClamPizza.java │ ├── NYStylePepperoniPizza.java │ ├── NYStyleVeggiePizza.java │ ├── Pizza.java │ ├── PizzaStore.java │ └── PizzaTestDrive.java ├── iterator ├── dinermerger │ ├── DinerMenu.java │ ├── DinerMenuIterator.java │ ├── Iterator.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── PancakeHouseMenu.java │ ├── PancakeHouseMenuIterator.java │ └── Waitress.java ├── dinermergercafe │ ├── CafeMenu.java │ ├── DinerMenu.java │ ├── DinerMenuIterator.java │ ├── Iterator.java │ ├── Menu.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── PancakeHouseMenu.java │ └── Waitress.java └── dinermergeri │ ├── DinerMenu.java │ ├── DinerMenuIterator.java │ ├── Iterator.java │ ├── Menu.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── PancakeHouseMenu.java │ └── Waitress.java ├── observer ├── swing │ └── SwingObserverExample.java ├── weather │ ├── CurrentConditionsDisplay.java │ ├── DisplayElement.java │ ├── ForecastDisplay.java │ ├── HeatIndexDisplay.java │ ├── Observer.java │ ├── StatisticsDisplay.java │ ├── Subject.java │ ├── WeatherData.java │ └── WeatherStation.java └── weatherobservable │ ├── CurrentConditionsDisplay.java │ ├── DisplayElement.java │ ├── ForecastDisplay.java │ ├── HeatIndexDisplay.java │ ├── StatisticsDisplay.java │ ├── WeatherData.java │ └── WeatherStation.java ├── proxy ├── gumball │ ├── GumballMachine.java │ ├── GumballMachineRemote.java │ ├── GumballMachineTestDrive.java │ ├── GumballMonitor.java │ ├── GumballMonitorTestDrive.java │ ├── HasQuarterState.java │ ├── NoQuarterState.java │ ├── SoldOutState.java │ ├── SoldState.java │ ├── State.java │ └── WinnerState.java ├── javaproxy │ ├── MatchMakingTestDrive.java │ ├── NonOwnerInvocationHandler.java │ ├── OwnerInvocationHandler.java │ ├── PersonBean.java │ └── PersonBeanImpl.java └── virtualproxy │ ├── ImageComponent.java │ ├── ImageProxy.java │ └── ImageProxyTestDrive.java ├── singleton ├── classic │ └── Singleton.java ├── doublecheckedlocking │ └── Singleton.java ├── static │ ├── Singleton.java │ └── SingletonClient.java ├── subclass │ ├── CoolerSingleton.java │ ├── HotterSingleton.java │ ├── Singleton.java │ └── SingletonTestDrive.java └── threadsafe │ └── Singleton.java ├── state ├── gumball │ ├── GumballMachine.java │ └── GumballMachineTestDrive.java ├── gumballstate │ ├── GumballMachine.java │ ├── GumballMachineTestDrive.java │ ├── HasQuarterState.java │ ├── NoQuarterState.java │ ├── SoldOutState.java │ ├── SoldState.java │ └── State.java └── gumballstatewinner │ ├── GumballMachine.java │ ├── GumballMachineTestDrive.java │ ├── HasQuarterState.java │ ├── NoQuarterState.java │ ├── SoldOutState.java │ ├── SoldState.java │ ├── State.java │ └── WinnerState.java ├── strategy ├── Duck.java ├── FlyBehavior.java ├── FlyNoWay.java ├── FlyRocketPowered.java ├── FlyWithWings.java ├── MallardDuck.java ├── MiniDuckSimulator.java ├── ModelDuck.java ├── MuteQuack.java ├── Quack.java ├── QuackBehavior.java └── Squeak.java └── templatemethod ├── applet ├── AppletSource.java └── MyApplet.java ├── barista ├── BeverageTestDrive.java ├── CaffeineBeverage.java ├── CaffeineBeverageWithHook.java ├── Coffee.java ├── CoffeeWithHook.java ├── Tea.java └── TeaWithHook.java ├── frame └── MyFrame.java ├── simplebarista ├── Barista.java ├── Coffee.java └── Tea.java └── sort ├── Duck.java └── DuckSortTestDrive.java /README.md: -------------------------------------------------------------------------------- 1 | # Head-First-Design-Patterns 2 | Code for the book Head First Design Patterns by Eric Freeman & Elizabeth Freeman 3 | 4 | ## Patterns 5 | * [Strategy](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/strategy) 6 | * [Observer](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/observer) 7 | * [Decorator](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/decorator) 8 | * [Factory](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/factory) 9 | * [Singleton](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/singleton) 10 | * [Command](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/command) 11 | * [Adapter](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/adapter) 12 | * [Facade](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/facade) 13 | * [Template Method](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/templatemethod) 14 | * [Iterator](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/iterator) 15 | * [Composite](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/composite) 16 | * [State](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/state) 17 | * [Proxy](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/proxy) 18 | 19 | * [Model-View-Controller](https://github.com/rowin1/Head-First-Design-Patterns/tree/master/java/compound/combined/djview) 20 | -------------------------------------------------------------------------------- /java/adapter/ducks/Duck.java: -------------------------------------------------------------------------------- 1 | public interface Duck { 2 | public void quack(); 3 | public void fly(); 4 | } -------------------------------------------------------------------------------- /java/adapter/ducks/DuckAdapter.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class DuckAdapter implements Turkey { 4 | Duck duck; 5 | Random rand; 6 | 7 | public DuckAdapter(Duck duck) { 8 | this.duck = duck; 9 | rand = new Random(); 10 | } 11 | 12 | public void gobble() { 13 | duck.quack(); 14 | } 15 | 16 | public void fly() { 17 | if (rand.nextInt(5) == 0) { 18 | duck.fly(); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /java/adapter/ducks/DuckTestDrive.java: -------------------------------------------------------------------------------- 1 | public class DuckTestDrive { 2 | 3 | public static void main(String[] args) { 4 | MallardDuck duck = new MallardDuck(); 5 | 6 | WildTurkey turkey = new WildTurkey(); 7 | Duck turkeyAdapter = new TurkeyAdapter(turkey); 8 | 9 | System.out.println("The Turkey says..."); 10 | turkey.gobble(); 11 | turkey.fly(); 12 | 13 | System.out.println("\nThe duck says..."); 14 | testDuck(duck); 15 | 16 | System.out.println("The TurkeyAdapter says..."); 17 | testDuck(turkeyAdapter); 18 | } 19 | 20 | static void testDuck(Duck duck) { 21 | duck.quack(); 22 | duck.fly(); 23 | } 24 | } -------------------------------------------------------------------------------- /java/adapter/ducks/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Duck { 2 | 3 | public void quack() { 4 | System.out.println("Quack"); 5 | } 6 | 7 | public void fly() { 8 | System.out.println("I'm flying"); 9 | } 10 | } -------------------------------------------------------------------------------- /java/adapter/ducks/Turkey.java: -------------------------------------------------------------------------------- 1 | public interface Turkey { 2 | public void gobble(); 3 | public void fly(); 4 | } -------------------------------------------------------------------------------- /java/adapter/ducks/TurkeyAdapter.java: -------------------------------------------------------------------------------- 1 | public class TurkeyAdapter implements Duck { 2 | Turkey turkey; 3 | 4 | public TurkeyAdapter(Turkey turkey) { 5 | this.turkey = turkey; 6 | } 7 | 8 | public void quack() { 9 | turkey.gobble(); 10 | } 11 | 12 | public void fly() { 13 | for (int i = 0; i < 5; i++) { 14 | turkey.fly(); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /java/adapter/ducks/TurkeyTestDrive.java: -------------------------------------------------------------------------------- 1 | public class TurkeyTestDrive { 2 | 3 | public static void main(String[] args) { 4 | WildTurkey turkey = new WildTurkey(); 5 | 6 | MallardDuck duck = new MallardDuck(); 7 | DuckAdapter duckAdapter = new DuckAdapter(duck); 8 | 9 | System.out.println("The Duck says..."); 10 | duck.quack(); 11 | duck.fly(); 12 | 13 | System.out.println("The Turkey says..."); 14 | testTurkey(turkey); 15 | 16 | System.out.println("The DuckAdapter says..."); 17 | testTurkey(duckAdapter); 18 | } 19 | 20 | static void testTurkey(Turkey turkey) { 21 | turkey.gobble(); 22 | turkey.fly(); 23 | } 24 | } -------------------------------------------------------------------------------- /java/adapter/ducks/WildTurkey.java: -------------------------------------------------------------------------------- 1 | public class WildTurkey implements Turkey { 2 | 3 | public void gobble() { 4 | System.out.println("Gobble gobble"); 5 | } 6 | 7 | public void fly() { 8 | System.out.println("I'm flying a short distance"); 9 | } 10 | } -------------------------------------------------------------------------------- /java/adapter/iterenum/EI.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class EI { 4 | public static void main (String args[]) { 5 | Vector v = new Vector(Arrays.asList(args)); 6 | 7 | Enumeration enumeration = v.elements(); 8 | while (enumeration.hasMoreElements()) { 9 | System.out.println(enumeration.nextElement()); 10 | } 11 | 12 | Iterator iterator = v.iterator(); 13 | while (iterator.hasNext()) { 14 | System.out.println(iterator.next()); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /java/adapter/iterenum/EnumerationIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class EnumerationIterator implements Iterator { 4 | Enumeration enumeration; 5 | 6 | public EnumerationIterator(Enumeration enumeration) { 7 | this.enumeration = enumeration; 8 | } 9 | 10 | public boolean hasNext() { 11 | return enumeration.hasMoreElements(); 12 | } 13 | 14 | public Object next() { 15 | return enumeration.nextElement(); 16 | } 17 | 18 | public void remove() { 19 | throw new UnsupportedOperationException(); 20 | } 21 | } -------------------------------------------------------------------------------- /java/adapter/iterenum/EnumerationIteratorTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class EnumerationIteratorTestDrive { 4 | public static void main (String args[]) { 5 | Vector v = new Vector(Arrays.asList(args)); 6 | Iterator iterator = new EnumerationIterator(v.elements()); 7 | while (iterator.hasNext()) { 8 | System.out.println(iterator.next()); 9 | } 10 | } 11 | } -------------------------------------------------------------------------------- /java/adapter/iterenum/IteratorEnumeration.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class IteratorEnumeration implements Enumeration { 4 | Iterator iterator; 5 | 6 | public IteratorEnumeration(Iterator iterator) { 7 | this.iterator = iterator; 8 | } 9 | 10 | public boolean hasMoreElements() { 11 | return iterator.hasNext(); 12 | } 13 | 14 | public Object nextElement() { 15 | return iterator.next(); 16 | } 17 | } -------------------------------------------------------------------------------- /java/adapter/iterenum/IteratorEnumerationTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class IteratorEnumerationTestDrive { 4 | 5 | public static void main (String[] args) { 6 | ArrayList l = new ArrayList(Arrays.asList(args)); 7 | Enumeration enumeration = new IteratorEnumeration(l.iterator()); 8 | while (enumeration.hasMoreElements()) { 9 | System.out.println(enumeration.nextElement()); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /java/command/party/CeilingFan.java: -------------------------------------------------------------------------------- 1 | public class CeilingFan { 2 | public static final int HIGH = 3; 3 | public static final int MEDIUM = 2; 4 | public static final int LOW = 1; 5 | public static final int OFF = 0; 6 | String location; 7 | int speed; 8 | 9 | public CeilingFan(String location) { 10 | this.location = location; 11 | } 12 | 13 | public void high() { 14 | speed = HIGH; 15 | System.out.println(location + " ceiling fan is on high"); 16 | } 17 | 18 | public void medium() { 19 | speed = MEDIUM; 20 | System.out.println(location + " ceiling fan is on medium"); 21 | } 22 | 23 | public void low() { 24 | speed = LOW; 25 | System.out.println(location + " ceiling fan is on low"); 26 | } 27 | 28 | public void off() { 29 | speed = OFF; 30 | System.out.println(location + " ceiling fan is off"); 31 | } 32 | 33 | public int getSpeed() { 34 | return speed; 35 | } 36 | } -------------------------------------------------------------------------------- /java/command/party/CeilingFanHighCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanHighCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanHighCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | 9 | public void execute() { 10 | prevSpeed = ceilingFan.getSpeed(); 11 | ceilingFan.high(); 12 | } 13 | 14 | public void undo() { 15 | switch (prevSpeed) { 16 | case CeilingFan.HIGH: 17 | ceilingFan.high(); 18 | break; 19 | case CeilingFan.MEDIUM: 20 | ceilingFan.medium(); 21 | break; 22 | case CeilingFan.LOW: 23 | ceilingFan.low(); 24 | break; 25 | default: 26 | ceilingFan.off(); 27 | break; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/command/party/CeilingFanMediumCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanMediumCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanMediumCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | public void execute() { 9 | prevSpeed = ceilingFan.getSpeed(); 10 | ceilingFan.medium(); 11 | } 12 | 13 | public void undo() { 14 | switch (prevSpeed) { 15 | case CeilingFan.HIGH: 16 | ceilingFan.high(); 17 | break; 18 | case CeilingFan.MEDIUM: 19 | ceilingFan.medium(); 20 | break; 21 | case CeilingFan.LOW: 22 | ceilingFan.low(); 23 | break; 24 | default: 25 | ceilingFan.off(); 26 | break; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/command/party/CeilingFanOffCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanOffCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanOffCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | 9 | public void execute() { 10 | prevSpeed = ceilingFan.getSpeed(); 11 | ceilingFan.off(); 12 | } 13 | 14 | public void undo() { 15 | switch (prevSpeed) { 16 | case CeilingFan.HIGH: 17 | ceilingFan.high(); 18 | break; 19 | case CeilingFan.MEDIUM: 20 | ceilingFan.medium(); 21 | break; 22 | case CeilingFan.LOW: 23 | ceilingFan.low(); 24 | break; 25 | default: 26 | ceilingFan.off(); 27 | break; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/command/party/Command.java: -------------------------------------------------------------------------------- 1 | public interface Command { 2 | public void execute(); 3 | public void undo(); 4 | } -------------------------------------------------------------------------------- /java/command/party/Hottub.java: -------------------------------------------------------------------------------- 1 | public class Hottub { 2 | boolean on; 3 | int temperature; 4 | 5 | public Hottub() { } 6 | 7 | public void on() { 8 | on = true; 9 | } 10 | 11 | public void off() { 12 | on = false; 13 | } 14 | 15 | public void circulate() { 16 | if (on) { 17 | System.out.println("Hottub is bubbling!"); 18 | } 19 | } 20 | 21 | public void jetsOn() { 22 | if (on) { 23 | System.out.println("Hottub jets are on"); 24 | } 25 | } 26 | 27 | public void jetsOff() { 28 | if (on) { 29 | System.out.println("Hottub jets are off"); 30 | } 31 | } 32 | 33 | public void setTemperature(int temperature) { 34 | if (temperature > this.temperature) { 35 | System.out.println("Hottub is heating to a steaming " + temperature + " degrees"); 36 | } 37 | else { 38 | System.out.println("Hottub is cooling to " + temperature + " degrees"); 39 | } 40 | this.temperature = temperature; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/command/party/HottubOffCommand.java: -------------------------------------------------------------------------------- 1 | public class HottubOffCommand implements Command { 2 | Hottub hottub; 3 | 4 | public HottubOffCommand(Hottub hottub) { 5 | this.hottub = hottub; 6 | } 7 | 8 | public void execute() { 9 | hottub.setTemperature(98); 10 | hottub.off(); 11 | } 12 | public void undo() { 13 | hottub.on(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/HottubOnCommand.java: -------------------------------------------------------------------------------- 1 | public class HottubOnCommand implements Command { 2 | Hottub hottub; 3 | 4 | public HottubOnCommand(Hottub hottub) { 5 | this.hottub = hottub; 6 | } 7 | 8 | public void execute() { 9 | hottub.on(); 10 | hottub.setTemperature(104); 11 | hottub.circulate(); 12 | } 13 | public void undo() { 14 | hottub.off(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/command/party/Light.java: -------------------------------------------------------------------------------- 1 | public class Light { 2 | String location; 3 | int level; 4 | 5 | public Light(String location) { 6 | this.location = location; 7 | } 8 | 9 | public void on() { 10 | level = 100; 11 | System.out.println("Light is on"); 12 | } 13 | 14 | public void off() { 15 | level = 0; 16 | System.out.println("Light is off"); 17 | } 18 | 19 | public void dim(int level) { 20 | this.level = level; 21 | if (level == 0) { 22 | off(); 23 | } 24 | else { 25 | System.out.println("Light is dimmed to " + level + "%"); 26 | } 27 | } 28 | 29 | public int getLevel() { 30 | return level; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/command/party/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOffCommand implements Command { 2 | Light light; 3 | 4 | public LightOffCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.off(); 10 | } 11 | 12 | public void undo() { 13 | light.on(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOnCommand implements Command { 2 | Light light; 3 | 4 | public LightOnCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.on(); 10 | } 11 | 12 | public void undo() { 13 | light.off(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/LightroomLightOffCommand.java: -------------------------------------------------------------------------------- 1 | public class LivingroomLightOffCommand implements Command { 2 | Light light; 3 | 4 | public LivingroomLightOffCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.off(); 10 | } 11 | 12 | public void undo() { 13 | light.on(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/LivingroomLightOnCommand.java: -------------------------------------------------------------------------------- 1 | public class LivingroomLightOnCommand implements Command { 2 | Light light; 3 | 4 | public LivingroomLightOnCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.on(); 10 | } 11 | 12 | public void undo() { 13 | light.off(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/MacroCommand.java: -------------------------------------------------------------------------------- 1 | public class MacroCommand implements Command { 2 | Command[] commands; 3 | 4 | public MacroCommand(Command[] commands) { 5 | this.commands = commands; 6 | } 7 | 8 | public void execute() { 9 | for (int i = 0; i < commands.length; i++) { 10 | commands[i].execute(); 11 | } 12 | } 13 | 14 | public void undo() { 15 | for (int i = commands.length -1; i >= 0; i--) { 16 | commands[i].undo(); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /java/command/party/NoCommand.java: -------------------------------------------------------------------------------- 1 | public class NoCommand implements Command { 2 | public void execute() { } 3 | public void undo() { } 4 | } -------------------------------------------------------------------------------- /java/command/party/RemoteControl.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class RemoteControl { 4 | Command[] onCommands; 5 | Command[] offCommands; 6 | Command undoCommand; 7 | 8 | public RemoteControl() { 9 | onCommands = new Command[7]; 10 | offCommands = new Command[7]; 11 | 12 | Command noCommand = new NoCommand(); 13 | for (int i = 0; i < 7; i++) { 14 | onCommands[i] = noCommand; 15 | offCommands[i] = noCommand; 16 | } 17 | undoCommand = noCommand; 18 | } 19 | 20 | public void setCommand(int slot, Command onCommand, Command offCommand) { 21 | onCommands[slot] = onCommand; 22 | offCommands[slot] = offCommand; 23 | } 24 | 25 | public void onButtonWasPushed(int slot) { 26 | onCommands[slot].execute(); 27 | undoCommand = onCommands[slot]; 28 | } 29 | 30 | public void offButtonWasPushed(int slot) { 31 | offCommands[slot].execute(); 32 | undoCommand = offCommands[slot]; 33 | } 34 | 35 | public void undoButtonWasPushed() { 36 | undoCommand.undo(); 37 | } 38 | 39 | public String toString() { 40 | StringBuffer stringBuff = new StringBuffer(); 41 | stringBuff.append("\n------ Remote Control -------\n"); 42 | for (int i = 0; i < onCommands.length; i++) { 43 | stringBuff.append("[slot " + i + "] " + onCommands[i].getClass().getName() 44 | + " " + offCommands[i].getClass().getName() + "\n"); 45 | } 46 | stringBuff.append("[undo] " + undoCommand.getClass().getName() + "\n"); 47 | return stringBuff.toString(); 48 | } 49 | } -------------------------------------------------------------------------------- /java/command/party/RemoteLoader.java: -------------------------------------------------------------------------------- 1 | public class RemoteLoader { 2 | 3 | public static void main(String[] args) { 4 | 5 | RemoteControl remoteControl = new RemoteControl(); 6 | 7 | Light light = new Light("Living Room"); 8 | TV tv = new TV("Living Room"); 9 | Stereo stereo = new Stereo("Living Room"); 10 | Hottub hottub = new Hottub(); 11 | 12 | LightOnCommand lightOn = new LightOnCommand(light); 13 | LightOffCommand lightOff = new LightOffCommand(light); 14 | StereoOnCommand stereoOn = new StereoOnCommand(stereo); 15 | StereoOffCommand stereoOff = new StereoOffCommand(stereo); 16 | TVOnCommand tvOn = new TVOnCommand(tv); 17 | TVOffCommand tvOff = new TVOffCommand(tv); 18 | HottubOnCommand hottubOn = new HottubOnCommand(hottub); 19 | HottubOffCommand hottubOff = new HottubOffCommand(hottub); 20 | 21 | Command[] partyOn = { lightOn, stereoOn, tvOn, hottubOn}; 22 | Command[] partyOff = { lightOff, stereoOff, tvOff, hottubOff}; 23 | 24 | MacroCommand partyOnMacro = new MacroCommand(partyOn); 25 | MacroCommand partyOffMacro = new MacroCommand(partyOff); 26 | 27 | remoteControl.setCommand(0, partyOnMacro, partyOffMacro); 28 | 29 | System.out.println(remoteControl); 30 | System.out.println("--- Pushing Macro On---"); 31 | remoteControl.onButtonWasPushed(0); 32 | System.out.println("--- Pushing Macro Off---"); 33 | remoteControl.offButtonWasPushed(0); 34 | } 35 | } -------------------------------------------------------------------------------- /java/command/party/Stereo.java: -------------------------------------------------------------------------------- 1 | public class Stereo { 2 | String location; 3 | 4 | public Stereo(String location) { 5 | this.location = location; 6 | } 7 | 8 | public void on() { 9 | System.out.println(location + " stereo is on"); 10 | } 11 | 12 | public void off() { 13 | System.out.println(location + " stereo is off"); 14 | } 15 | 16 | public void setCD() { 17 | System.out.println(location + " stereo is set for CD input"); 18 | } 19 | 20 | public void setDVD() { 21 | System.out.println(location + " stereo is set for DVD input"); 22 | } 23 | 24 | public void setRadio() { 25 | System.out.println(location + " stereo is set for Radio"); 26 | } 27 | 28 | public void setVolume(int volume) { 29 | System.out.println(location + " Stereo volume set to " + volume); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/command/party/StereoOffCommand.java: -------------------------------------------------------------------------------- 1 | public class StereoOffCommand implements Command { 2 | Stereo stereo; 3 | 4 | public StereoOffCommand(Stereo stereo) { 5 | this.stereo = stereo; 6 | } 7 | 8 | public void execute() { 9 | stereo.off(); 10 | } 11 | 12 | public void undo() { 13 | stereo.on(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/StereoOnCommand.java: -------------------------------------------------------------------------------- 1 | public class StereoOnCommand implements Command { 2 | Stereo stereo; 3 | 4 | public StereoOnCommand(Stereo stereo) { 5 | this.stereo = stereo; 6 | } 7 | 8 | public void execute() { 9 | stereo.on(); 10 | } 11 | 12 | public void undo() { 13 | stereo.off(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/StereoOnWithCDCommand.java: -------------------------------------------------------------------------------- 1 | public class StereoOnWithCDCommand implements Command { 2 | Stereo stereo; 3 | 4 | public StereoOnWithCDCommand(Stereo stereo) { 5 | this.stereo = stereo; 6 | } 7 | 8 | public void execute() { 9 | stereo.on(); 10 | stereo.setCD(); 11 | stereo.setVolume(11); 12 | } 13 | 14 | public void undo() { 15 | stereo.off(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/command/party/TV.java: -------------------------------------------------------------------------------- 1 | public class TV { 2 | String location; 3 | int channel; 4 | 5 | public TV(String location) { 6 | this.location = location; 7 | } 8 | 9 | public void on() { 10 | System.out.println(location + " TV is On"); 11 | } 12 | 13 | public void off() { 14 | System.out.println(location + " TV is Off"); 15 | } 16 | 17 | public void setInputChannel() { 18 | this.channel = 3; 19 | System.out.println(location + " TV channel is set for DVD"); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/command/party/TVOffCommand.java: -------------------------------------------------------------------------------- 1 | public class TVOffCommand implements Command { 2 | TV tv; 3 | 4 | public TVOffCommand(TV tv) { 5 | this.tv= tv; 6 | } 7 | 8 | public void execute() { 9 | tv.off(); 10 | } 11 | 12 | public void undo() { 13 | tv.on(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/command/party/TVOnCommand.java: -------------------------------------------------------------------------------- 1 | public class TVOnCommand implements Command { 2 | TV tv; 3 | 4 | public TVOnCommand(TV tv) { 5 | this.tv = tv; 6 | } 7 | 8 | public void execute() { 9 | tv.on(); 10 | tv.setInputChannel(); 11 | } 12 | 13 | public void undo() { 14 | tv.off(); 15 | } 16 | } -------------------------------------------------------------------------------- /java/command/remote/CeilingFan.java: -------------------------------------------------------------------------------- 1 | public class CeilingFan { 2 | String location = ""; 3 | int level; 4 | public static final int HIGH = 2; 5 | public static final int MEDIUM = 1; 6 | public static final int LOW = 0; 7 | 8 | public CeilingFan(String location) { 9 | this.location = location; 10 | } 11 | 12 | public void high() { 13 | // turns the ceiling fan on to high 14 | level = HIGH; 15 | System.out.println(location + " ceiling fan is on high"); 16 | 17 | } 18 | 19 | public void medium() { 20 | // turns the ceiling fan on to medium 21 | level = MEDIUM; 22 | System.out.println(location + " ceiling fan is on medium"); 23 | } 24 | 25 | public void low() { 26 | level = LOW; 27 | System.out.println(location + " ceiling fan is on low"); 28 | } 29 | 30 | public void off() { 31 | // turns the ceiling fan off 32 | level = 0; 33 | System.out.println(location + " ceiling fan is off"); 34 | } 35 | 36 | public int getSpeed() { 37 | return level; 38 | } 39 | 40 | 41 | } -------------------------------------------------------------------------------- /java/command/remote/CeilingFanOffCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanOffCommand implements Command { 2 | CeilingFan ceilingFan; 3 | 4 | public CeilingFanOffCommand(CeilingFan ceilingFan) { 5 | this.ceilingFan = ceilingFan; 6 | } 7 | 8 | public void execute() { 9 | ceilingFan.off(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/CeilingFanOnCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanOnCommand implements Command { 2 | CeilingFan ceilingFan; 3 | 4 | public CeilingFanOnCommand(CeilingFan ceilingFan) { 5 | this.ceilingFan = ceilingFan; 6 | } 7 | 8 | public void execute() { 9 | ceilingFan.high(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/Command.java: -------------------------------------------------------------------------------- 1 | public interface Command { 2 | public void execute(); 3 | } -------------------------------------------------------------------------------- /java/command/remote/GarageDoor.java: -------------------------------------------------------------------------------- 1 | public class GarageDoor { 2 | String location; 3 | 4 | public GarageDoor(String location) { 5 | this.location = location; 6 | } 7 | 8 | public void up() { 9 | System.out.println("Garage Door is Open"); 10 | } 11 | 12 | public void down() { 13 | System.out.println("Garage Door is Closed"); 14 | } 15 | 16 | public void stop() { 17 | System.out.println("Garage door is Stopped"); 18 | } 19 | 20 | public void lightOn() { 21 | System.out.println("Garage light is On"); 22 | } 23 | 24 | public void lightOff() { 25 | System.out.println("Garage light is Off"); 26 | } 27 | } -------------------------------------------------------------------------------- /java/command/remote/GarageDoorDownCommand.java: -------------------------------------------------------------------------------- 1 | public class GarageDoorDownCommand implements Command { 2 | GarageDoor garageDoor; 3 | 4 | public GarageDoorDownCommand(GarageDoor garageDoor) { 5 | this.garageDoor = garageDoor; 6 | } 7 | 8 | public void execute() { 9 | garageDoor.down(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/GarageDoorUpCommand.java: -------------------------------------------------------------------------------- 1 | public class GarageDoorUpCommand implements Command { 2 | GarageDoor garageDoor; 3 | 4 | public GarageDoorUpCommand(GarageDoor garageDoor) { 5 | this.garageDoor = garageDoor; 6 | } 7 | 8 | public void execute() { 9 | garageDoor.up(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/Hottub.java: -------------------------------------------------------------------------------- 1 | public class Hottub { 2 | boolean on; 3 | int temperature; 4 | 5 | public Hottub() { 6 | } 7 | 8 | public void on() { 9 | on = true; 10 | } 11 | 12 | public void off() { 13 | on = false; 14 | } 15 | 16 | public void bubblesOn() { 17 | if (on) { 18 | System.out.println("Hottub is bubbling!"); 19 | } 20 | } 21 | 22 | public void bubblesOff() { 23 | if (!on) { 24 | System.out.println("Hottub is not bubbling"); 25 | } 26 | } 27 | 28 | public void jetsOn() { 29 | if (on) { 30 | System.out.println("Hottub jets are on"); 31 | } 32 | } 33 | 34 | public void jetsOff() { 35 | if (!on) { 36 | System.out.println("Hottub jets are off"); 37 | } 38 | } 39 | 40 | public void setTemperature(int temperature) { 41 | this.temperature = temperature; 42 | } 43 | 44 | public void heat() { 45 | temperature = 105; 46 | System.out.println("Hottub is heating to a steaming 105 degrees"); 47 | } 48 | 49 | public void cool() { 50 | temperature = 98; 51 | System.out.println("Hottub is cooling to 98 degrees"); 52 | } 53 | } -------------------------------------------------------------------------------- /java/command/remote/HottubOffCommand.java: -------------------------------------------------------------------------------- 1 | public class HottubOffCommand implements Command { 2 | Hottub hottub; 3 | 4 | public HottubOffCommand(Hottub hottub) { 5 | this.hottub = hottub; 6 | } 7 | 8 | public void execute() { 9 | hottub.cool(); 10 | hottub.off(); 11 | hottub.bubblesOff(); 12 | } 13 | } -------------------------------------------------------------------------------- /java/command/remote/HottubOnCommand.java: -------------------------------------------------------------------------------- 1 | public class HottubOnCommand implements Command { 2 | Hottub hottub; 3 | 4 | public HottubOnCommand(Hottub hottub) { 5 | this.hottub = hottub; 6 | } 7 | 8 | public void execute() { 9 | hottub.heat(); 10 | hottub.on(); 11 | hottub.bubblesOn(); 12 | } 13 | } -------------------------------------------------------------------------------- /java/command/remote/Light.java: -------------------------------------------------------------------------------- 1 | public class Light { 2 | String location; 3 | 4 | public Light(String location) { 5 | this.location = location; 6 | } 7 | 8 | public void on() { 9 | System.out.println(location + " Light is On"); 10 | } 11 | 12 | public void off() { 13 | System.out.println(location + " Light is Off"); 14 | } 15 | } -------------------------------------------------------------------------------- /java/command/remote/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOffCommand implements Command { 2 | Light light; 3 | 4 | public LightOffCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.off(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOnCommand implements Command { //Command object 2 | Light light; // The receiver 3 | 4 | public LightOnCommand(Light light) { 5 | this.light = light; // Pass receiver into Command constructor 6 | } 7 | 8 | public void execute() { 9 | light.on(); // Calling the action on the receiver 10 | } 11 | } 12 | 13 | // The actions and the receiver are bound together in the command object -------------------------------------------------------------------------------- /java/command/remote/LivingroomLightOffCommand.java: -------------------------------------------------------------------------------- 1 | public LivingroomLightOffCommand implements Command { 2 | Light light; 3 | 4 | public LivingroomLightOffCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.off(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/LivingroomLightOnCommand.java: -------------------------------------------------------------------------------- 1 | public LivingroomLightOnCommand implements Command { 2 | Light light; 3 | 4 | public LivingroomLightOnCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.on(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/NoCommand.java: -------------------------------------------------------------------------------- 1 | public class NoCommand implements Command { 2 | public void execute() { } 3 | } -------------------------------------------------------------------------------- /java/command/remote/RemoteControl.java: -------------------------------------------------------------------------------- 1 | public class RemoteControl { 2 | Command[] onCommands; 3 | Command[] offCommands; 4 | 5 | public RemoteControl() { 6 | onCommands = new Command[7]; 7 | offCommands = new Command[7]; 8 | 9 | Command noCommand = new NoCommand(); 10 | for (int i = 0; i < 7; i++) { 11 | onCommands[i] = noCommand; 12 | offCommands[i] = noCommand; 13 | } 14 | } 15 | 16 | public void setCommand(int slot, Command onCommand, Command offCommand) { 17 | onCommands[slot] = onCommand; 18 | offCommands[slot] = offCommand; 19 | } 20 | 21 | public void onButtonWasPushed(int slot) { 22 | onCommands[slot].execute(); 23 | } 24 | 25 | public void offButtonWasPushed(int slot) { 26 | offCommands[slot].execute(); 27 | } 28 | 29 | public String toString() { 30 | StringBuffer stringBuff = new StringBuffer(); 31 | stringBuff.append("\n------ Remote Control -------\n"); 32 | for (int i = 0; i < onCommands.length; i++) { 33 | stringBuff.append("[slot " + i + "] " + onCommands[i].getClass().getName() 34 | + " " + offCommands[i].getClass().getName() + "\n"); 35 | } 36 | return stringBuff.toString(); 37 | } 38 | } -------------------------------------------------------------------------------- /java/command/remote/Stereo.java: -------------------------------------------------------------------------------- 1 | public class Stereo { 2 | int volume; 3 | String location; 4 | 5 | public Stereo(String location) { 6 | this.location = location; 7 | } 8 | 9 | public void on() { 10 | System.out.println(location + " Stereo is On"); 11 | } 12 | 13 | public void off() { 14 | System.out.println(location + " Stereo is Off"); 15 | } 16 | 17 | public void setCD() { 18 | System.out.println(location + " Stereo is set for CD input"); 19 | } 20 | 21 | public void setDVD() { 22 | System.out.println(location + " Stereo is set for DVD input"); 23 | } 24 | 25 | public void setVolume(int volume) { 26 | this.volume = volume; 27 | System.out.println(location + " Stereo Volume is set to " + volume); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/command/remote/StereoOffCommand.java: -------------------------------------------------------------------------------- 1 | public class StereoOffCommand implements Command { 2 | Stereo stereo; 3 | 4 | public StereoOffCommand(Stereo stereo) { 5 | this.stereo = stereo; 6 | } 7 | 8 | public void execute() { 9 | stereo.off(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/remote/StereoOnWithCDCommand.java: -------------------------------------------------------------------------------- 1 | public class StereoOnWithCDCommand implements Command { 2 | Stereo stereo; 3 | 4 | public StereoOnWithCDCommand(Stereo stereo) { 5 | this.stereo = stereo; 6 | } 7 | 8 | public void execute() { 9 | stereo.on(); 10 | stereo.setCD(); 11 | stereo.setVolume(11); 12 | } 13 | } -------------------------------------------------------------------------------- /java/command/remote/TV.java: -------------------------------------------------------------------------------- 1 | public class TV { 2 | String location; 3 | int channel; 4 | 5 | public TV(String location) { 6 | this.location = location; 7 | } 8 | 9 | public void on() { 10 | System.out.println("TV is on"); 11 | } 12 | 13 | public void off() { 14 | System.out.println("TV is off"); 15 | } 16 | 17 | public void setInputChannel() { 18 | this.channel = 3; 19 | System.out.println("Channel is set for VCR"); 20 | } 21 | } -------------------------------------------------------------------------------- /java/command/simpleremote/Command.java: -------------------------------------------------------------------------------- 1 | public interface Command { 2 | public void execute(); 3 | } -------------------------------------------------------------------------------- /java/command/simpleremote/GarageDoor.java: -------------------------------------------------------------------------------- 1 | public class GarageDoor { 2 | 3 | public GarageDoor() {} 4 | 5 | public void up() { 6 | System.out.println("Garage Door is Open"); 7 | } 8 | 9 | public void down() { 10 | System.out.println("Garage Door is Closed"); 11 | } 12 | 13 | public void stop() { 14 | System.out.println("Garage door is Stopped"); 15 | } 16 | 17 | public void lightOn() { 18 | System.out.println("Garage light is On"); 19 | } 20 | 21 | public void lightOff() { 22 | System.out.println("Garage light is Off"); 23 | } 24 | } -------------------------------------------------------------------------------- /java/command/simpleremote/GarageDoorOpenCommand.java: -------------------------------------------------------------------------------- 1 | public class GarageDoorOpenCommand implements Command { 2 | GarageDoor garageDoor; 3 | 4 | public GarageDoorOpenCommand(GarageDoor garageDoor) { 5 | this.garageDoor = garageDoor; 6 | } 7 | 8 | public void execute() { 9 | garageDoor.up(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/simpleremote/Light.java: -------------------------------------------------------------------------------- 1 | public class Light { 2 | 3 | public Light() {} 4 | 5 | public void on() { 6 | System.out.println("Light is On"); 7 | } 8 | 9 | public void off() { 10 | System.out.println("Light is Off"); 11 | } 12 | } -------------------------------------------------------------------------------- /java/command/simpleremote/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOffCommand implements Command { 2 | Light light; 3 | 4 | public LightOffCommand(Light light) { 5 | this.light = light; 6 | } 7 | 8 | public void execute() { 9 | light.off(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/command/simpleremote/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOnCommand implements Command { 2 | Light light; // The receiver 3 | 4 | public LightOnCommand(Light light) { 5 | this.light = light; // Pass receiver into Command constructor 6 | } 7 | 8 | public void execute() { 9 | light.on(); // Calling the action on the receiver 10 | } 11 | } 12 | 13 | // The actions and the receiver are bound together in the command object -------------------------------------------------------------------------------- /java/command/simpleremote/RemoteControlTest.java: -------------------------------------------------------------------------------- 1 | public class RemoteControlTest { // This is our Client in Command Pattern-Speak 2 | 3 | public static void main(String[] args) { 4 | SimpleRemoteControl remote = new SimpleRemoteControl(); // The remote is our Invoker; it will be passed a command object with 'setCommand' that can be used to make requests 5 | Light light = new Light(); // Create object that will be receiver 6 | LightOnCommand lightOn = new LightOnCommand(light); // create a command and pass the Receiver to it 7 | 8 | GarageDoor garageDoor = new GarageDoor(); 9 | GarageDoorOpenCommand garageOpen = new GarageDoorOpenCommand(garageDoor); 10 | 11 | remote.setCommand(lightOn); // Pass the command to the Invoker. 12 | remote.buttonWasPressed(); 13 | 14 | remote.setCommand(garageOpen); 15 | remote.buttonWasPressed(); 16 | } 17 | } -------------------------------------------------------------------------------- /java/command/simpleremote/SimpleRemoteControl.java: -------------------------------------------------------------------------------- 1 | public class SimpleRemoteControl { // Invoker class. Invoker has a reference to command object 2 | Command slot; // We have one slot to hold our command, which will control one device. 3 | 4 | public SimpleRemoteControl() {} 5 | 6 | public void setCommand(Command command) { 7 | slot = command; 8 | } 9 | 10 | public void buttonWasPressed() { 11 | slot.execute(); 12 | } 13 | } -------------------------------------------------------------------------------- /java/command/undo/CeilingFan.java: -------------------------------------------------------------------------------- 1 | public class CeilingFan { 2 | public static final int HIGH = 3; 3 | public static final int MEDIUM = 2; 4 | public static final int LOW = 1; 5 | public static final int OFF = 0; 6 | String location; 7 | int speed; 8 | 9 | public CeilingFan(String location) { 10 | this.location = location; 11 | speed = OFF; 12 | } 13 | 14 | public void high() { 15 | speed = HIGH; 16 | System.out.println(location + " ceiling fan is on high"); 17 | } 18 | 19 | public void medium() { 20 | speed = MEDIUM; 21 | System.out.println(location + " ceiling fan is on medium"); 22 | } 23 | 24 | public void low() { 25 | speed = LOW; 26 | System.out.println(location + " ceiling fan is on low"); 27 | } 28 | 29 | public void off() { 30 | speed = OFF; 31 | System.out.println(location + " ceiling fan is off"); 32 | } 33 | 34 | public int getSpeed() { 35 | return speed; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/command/undo/CeilingFanHighCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanHighCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanHighCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | 9 | public void execute() { 10 | prevSpeed = ceilingFan.getSpeed(); 11 | ceilingFan.high(); 12 | } 13 | 14 | public void undo() { 15 | if (prevSpeed == CeilingFan.HIGH) { 16 | ceilingFan.high(); 17 | } else if (prevSpeed == CeilingFan.MEDIUM) { 18 | ceilingFan.medium(); 19 | } else if (prevSpeed == CeilingFan.LOW) { 20 | ceilingFan.low(); 21 | } else if (prevSpeed == CeilingFan.OFF) { 22 | ceilingFan.off(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/command/undo/CeilingFanLowCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanLowCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanLowCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | 9 | public void execute() { 10 | prevSpeed = ceilingFan.getSpeed(); 11 | ceilingFan.low(); 12 | } 13 | 14 | public void undo() { 15 | if (prevSpeed == CeilingFan.HIGH) { 16 | ceilingFan.high(); 17 | } else if (prevSpeed == CeilingFan.MEDIUM) { 18 | ceilingFan.medium(); 19 | } else if (prevSpeed == CeilingFan.LOW) { 20 | ceilingFan.low(); 21 | } else if (prevSpeed == CeilingFan.OFF) { 22 | ceilingFan.off(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/command/undo/CeilingFanMediumCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanMediumCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanMediumCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | 9 | public void execute() { 10 | prevSpeed = ceilingFan.getSpeed(); 11 | ceilingFan.medium(); 12 | } 13 | 14 | public void undo() { 15 | if (prevSpeed == CeilingFan.HIGH) { 16 | ceilingFan.high(); 17 | } else if (prevSpeed == CeilingFan.MEDIUM) { 18 | ceilingFan.medium(); 19 | } else if (prevSpeed == CeilingFan.LOW) { 20 | ceilingFan.low(); 21 | } else if (prevSpeed == CeilingFan.OFF) { 22 | ceilingFan.off(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/command/undo/CeilingFanOffCommand.java: -------------------------------------------------------------------------------- 1 | public class CeilingFanOffCommand implements Command { 2 | CeilingFan ceilingFan; 3 | int prevSpeed; 4 | 5 | public CeilingFanOffCommand(CeilingFan ceilingFan) { 6 | this.ceilingFan = ceilingFan; 7 | } 8 | 9 | public void execute() { 10 | prevSpeed = ceilingFan.getSpeed(); 11 | ceilingFan.off(); 12 | } 13 | 14 | public void undo() { 15 | if (prevSpeed == CeilingFan.HIGH) { 16 | ceilingFan.high(); 17 | } else if (prevSpeed == CeilingFan.MEDIUM) { 18 | ceilingFan.medium(); 19 | } else if (prevSpeed == CeilingFan.LOW) { 20 | ceilingFan.low(); 21 | } else if (prevSpeed == CeilingFan.OFF) { 22 | ceilingFan.off(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/command/undo/Command.java: -------------------------------------------------------------------------------- 1 | public interface Command { 2 | public void execute(); 3 | public void undo(); 4 | } -------------------------------------------------------------------------------- /java/command/undo/DimmerLightOffCommand.java: -------------------------------------------------------------------------------- 1 | public class DimmerLightOffCommand implements Command { 2 | Light light; 3 | int prevLevel; 4 | 5 | public DimmerLightOffCommand(Light light) { 6 | this.light = light; 7 | prevLevel = 100; 8 | } 9 | 10 | public void execute() { 11 | prevLevel = light.getLevel(); 12 | light.off(); 13 | } 14 | 15 | public void undo() { 16 | light.dim(prevLevel); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/command/undo/DimmerLightOnCommand.java: -------------------------------------------------------------------------------- 1 | public class DimmerLightOnCommand implements Command { 2 | Light light; 3 | int prevLevel; 4 | 5 | public DimmerLightOnCommand(Light light) { 6 | this.light = light; 7 | } 8 | 9 | public void execute() { 10 | prevLevel = light.getLevel(); 11 | light.dim(75); 12 | } 13 | 14 | public void undo() { 15 | light.dim(prevLevel); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/command/undo/Light.java: -------------------------------------------------------------------------------- 1 | public class Light { 2 | String location; 3 | int level; 4 | 5 | public Light(String location) { 6 | this.location = location; 7 | } 8 | 9 | public void on() { 10 | level = 100; 11 | System.out.println("Light is on"); 12 | } 13 | 14 | public void off() { 15 | level = 0; 16 | System.out.println("Light is off"); 17 | } 18 | 19 | public void dim(int level) { 20 | this.level = level; 21 | if (level == 0) { 22 | off(); 23 | } 24 | else if (level == 100) { 25 | on(); 26 | } 27 | else { 28 | System.out.println("Light is dimmed to " + level + "%"); 29 | } 30 | } 31 | 32 | public int getLevel() { 33 | return level; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/command/undo/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOffCommand implements Command { 2 | Light light; 3 | int level; 4 | 5 | public LightOffCommand(Light light) { 6 | this.light = light; 7 | } 8 | 9 | public void execute() { 10 | level = light.getLevel(); 11 | light.off(); 12 | } 13 | 14 | public void undo() { 15 | light.dim(level); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/command/undo/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | public class LightOnCommand implements Command { 2 | Light light; 3 | int level; 4 | 5 | public LightOnCommand(Light light) { 6 | this.light = light; 7 | } 8 | 9 | public void execute() { 10 | level = light.getLevel(); 11 | light.on(); 12 | } 13 | 14 | public void undo() { 15 | light.dim(level); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/command/undo/NoCommand.java: -------------------------------------------------------------------------------- 1 | public class NoCommand implements Command { 2 | public void execute() { } 3 | public void undo() { } 4 | } -------------------------------------------------------------------------------- /java/command/undo/RemoteControlWithUndo.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class RemoteControlWithUndo { 4 | Command[] onCommands; 5 | Command[] offCommands; 6 | Command undoCommand; 7 | 8 | public RemoteControlWithUndo() { 9 | onCommands = new Command[7]; 10 | offCommands = new Command[7]; 11 | 12 | Command noCommand = new NoCommand(); 13 | for(int i=0;i<7;i++) { 14 | onCommands[i] = noCommand; 15 | offCommands[i] = noCommand; 16 | } 17 | undoCommand = noCommand; 18 | } 19 | 20 | public void setCommand(int slot, Command onCommand, Command offCommand) { 21 | onCommands[slot] = onCommand; 22 | offCommands[slot] = offCommand; 23 | } 24 | 25 | public void onButtonWasPushed(int slot) { 26 | onCommands[slot].execute(); 27 | undoCommand = onCommands[slot]; 28 | } 29 | 30 | public void offButtonWasPushed(int slot) { 31 | offCommands[slot].execute(); 32 | undoCommand = offCommands[slot]; 33 | } 34 | 35 | public void undoButtonWasPushed() { 36 | undoCommand.undo(); 37 | } 38 | 39 | public String toString() { 40 | StringBuffer stringBuff = new StringBuffer(); 41 | stringBuff.append("\n------ Remote Control -------\n"); 42 | for (int i = 0; i < onCommands.length; i++) { 43 | stringBuff.append("[slot " + i + "] " + onCommands[i].getClass().getName() 44 | + " " + offCommands[i].getClass().getName() + "\n"); 45 | } 46 | stringBuff.append("[undo] " + undoCommand.getClass().getName() + "\n"); 47 | return stringBuff.toString(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/command/undo/RemoteLoader.java: -------------------------------------------------------------------------------- 1 | public class RemoteLoader { 2 | 3 | public static void main(String[] args) { 4 | RemoteControlWithUndo remoteControl = new RemoteControlWithUndo(); 5 | 6 | Light livingRoomLight = new Light("Living Room"); 7 | 8 | LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight); 9 | LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight); 10 | 11 | remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff); 12 | 13 | remoteControl.onButtonWasPushed(0); 14 | remoteControl.offButtonWasPushed(0); 15 | System.out.println(remoteControl); 16 | remoteControl.undoButtonWasPushed(); 17 | remoteControl.offButtonWasPushed(0); 18 | remoteControl.onButtonWasPushed(0); 19 | System.out.println(remoteControl); 20 | remoteControl.undoButtonWasPushed(); 21 | 22 | CeilingFan ceilingFan = new CeilingFan("Living Room"); 23 | 24 | CeilingFanMediumCommand ceilingFanMedium = new CeilingFanMediumCommand(ceilingFan); 25 | CeilingFanHighCommand ceilingFanHigh = new CeilingFanHighCommand(ceilingFan); 26 | CeilingFanOffCommand ceilingFanOff = new CeilingFanOffCommand(ceilingFan); 27 | 28 | remoteControl.setCommand(0, ceilingFanMedium, ceilingFanOff); 29 | remoteControl.setCommand(1, ceilingFanHigh, ceilingFanOff); 30 | 31 | remoteControl.onButtonWasPushed(0); 32 | remoteControl.offButtonWasPushed(0); 33 | System.out.println(remoteControl); 34 | remoteControl.undoButtonWasPushed(); 35 | 36 | remoteControl.onButtonWasPushed(1); 37 | System.out.println(remoteControl); 38 | remoteControl.undoButtonWasPushed(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /java/composite/menu/Menu.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Menu extends MenuComponent { 5 | ArrayList menuComponents = new ArrayList(); 6 | String name; 7 | String description; 8 | 9 | public Menu(String name, String description) { 10 | this.name = name; 11 | this.description = description; 12 | } 13 | 14 | public void add(MenuComponent menuComponent) { 15 | menuComponents.add(menuComponent); 16 | } 17 | 18 | public void remove(MenuComponent menuComponent) { 19 | menuComponents.remove(menuComponent); 20 | } 21 | 22 | public MenuComponent getChild(int i) { 23 | return (MenuComponent)menuComponents.get(i); 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public String getDescription() { 31 | return description; 32 | } 33 | 34 | public void print() { 35 | System.out.println("\n" + getName()); 36 | System.out.println(", " + getDescription()); 37 | System.out.println("---------------------"); 38 | 39 | Iterator iterator = menuComponents.iterator(); 40 | while (iterator.hasNext()) { 41 | MenuComponent menuComponent = (MenuComponent)iterator.next(); 42 | menuComponent.print(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /java/composite/menu/MenuComponent.java: -------------------------------------------------------------------------------- 1 | public abstract class MenuComponent { 2 | 3 | public void add(MenuComponent menuComponent) { 4 | throw new UnsupportedOperationException(); 5 | } 6 | 7 | public void remove(MenuComponent menuComponent) { 8 | throw new UnsupportedOperationException(); 9 | } 10 | 11 | public MenuComponent getChild(int i) { 12 | throw new UnsupportedOperationException(); 13 | } 14 | 15 | public String getName() { 16 | throw new UnsupportedOperationException(); 17 | } 18 | 19 | public String getDescription() { 20 | throw new UnsupportedOperationException(); 21 | } 22 | 23 | public double getPrice() { 24 | throw new UnsupportedOperationException(); 25 | } 26 | 27 | public boolean isVegetarian() { 28 | throw new UnsupportedOperationException(); 29 | } 30 | 31 | public void print() { 32 | throw new UnsupportedOperationException(); 33 | } 34 | } -------------------------------------------------------------------------------- /java/composite/menu/MenuItem.java: -------------------------------------------------------------------------------- 1 | public class MenuItem extends MenuComponent { 2 | String name; 3 | String description; 4 | boolean vegetarian; 5 | double price; 6 | 7 | public MenuItem(String name, 8 | String description, 9 | boolean vegetarian, 10 | double price) { 11 | this.name = name; 12 | this.description = description; 13 | this.vegetarian = vegetarian; 14 | this.price = price; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public String getDescription() { 22 | return description; 23 | } 24 | 25 | public boolean isVegetarian() { 26 | return vegetarian; 27 | } 28 | 29 | public double getPrice() { 30 | return price; 31 | } 32 | 33 | public void print() { 34 | System.out.print(" " + getName()); 35 | if (isVegetarian()) { 36 | System.out.println("(v)"); 37 | } 38 | System.out.println(", " + getPrice()); 39 | System.out.println(" -- " + getDescription()); 40 | } 41 | } -------------------------------------------------------------------------------- /java/composite/menu/Waitress.java: -------------------------------------------------------------------------------- 1 | public class Waitress { 2 | MenuComponent allMenus; 3 | 4 | public Waitress(MenuComponent allMenus) { 5 | this.allMenus = allMenus; 6 | } 7 | 8 | public void printMenu() { 9 | allMenus.print(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/composite/menuiterator/CompositeIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.Iterator; 3 | 4 | public class CompositeIterator implements Iterator { 5 | Stack stack = new Stack(); 6 | 7 | public CompositeIterator(Iterator iterator) { 8 | stack.push(iterator); 9 | } 10 | 11 | public Object next() { 12 | if (hasNext()) { 13 | Iterator iterator = (Iterator)stack.peek(); 14 | MenuComponent menuComponent = (MenuComponent)iterator.next(); 15 | if (menuComponent instanceof Menu) { 16 | stack.push(menuComponent.createIterator()); 17 | } 18 | return menuComponent; 19 | } else { 20 | return null; 21 | } 22 | } 23 | 24 | public boolean hasNext() { 25 | if (stack.empty()) { 26 | return false; 27 | } 28 | else { 29 | Iterator iterator = (Iterator)stack.peek(); 30 | if (!iterator.hasNext()) { 31 | stack.pop(); 32 | return hasNext(); 33 | } 34 | else { 35 | return true; 36 | } 37 | } 38 | } 39 | 40 | public void remove() { 41 | throw new UnsupportedOperationException(); 42 | } 43 | } -------------------------------------------------------------------------------- /java/composite/menuiterator/Menu.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Menu extends MenuComponent { 5 | Iterator iterator = null; 6 | ArrayList menuComponents = new ArrayList(); 7 | String name; 8 | String description; 9 | 10 | public Menu(String name, String description) { 11 | this.name = name; 12 | this.description = description; 13 | } 14 | 15 | public void add(MenuComponent menuComponent) { 16 | menuComponents.add(menuComponent); 17 | } 18 | 19 | public void remove(MenuComponent menuComponent) { 20 | menuComponents.remove(menuComponent); 21 | } 22 | 23 | public MenuComponent getChild(int i) { 24 | return (MenuComponent)menuComponents.get(i); 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public String getDescription() { 32 | return description; 33 | } 34 | 35 | public Iterator createIterator() { 36 | if (iterator == null) { 37 | iterator = new CompositeIterator(menuComponents.iterator()); 38 | } 39 | return iterator; 40 | } 41 | 42 | public void print() { 43 | System.out.println("\n" + getName()); 44 | System.out.println(", " + getDescription()); 45 | System.out.println("---------------------"); 46 | 47 | Iterator iterator = menuComponents.iterator(); 48 | while (iterator.hasNext()) { 49 | MenuComponent menuComponent = (MenuComponent)iterator.next(); 50 | menuComponent.print(); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /java/composite/menuiterator/MenuComponent.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public abstract class MenuComponent { 4 | 5 | public void add(MenuComponent menuComponent) { 6 | throw new UnsupportedOperationException(); 7 | } 8 | 9 | public void remove(MenuComponent menuComponent) { 10 | throw new UnsupportedOperationException(); 11 | } 12 | 13 | public MenuComponent getChild(int i) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | public String getName() { 18 | throw new UnsupportedOperationException(); 19 | } 20 | 21 | public String getDescription() { 22 | throw new UnsupportedOperationException(); 23 | } 24 | 25 | public double getPrice() { 26 | throw new UnsupportedOperationException(); 27 | } 28 | 29 | public boolean isVegetarian() { 30 | throw new UnsupportedOperationException(); 31 | } 32 | 33 | public void print() { 34 | throw new UnsupportedOperationException(); 35 | } 36 | 37 | public Iterator createIterator() { 38 | throw new UnsupportedOperationException(); 39 | } 40 | } -------------------------------------------------------------------------------- /java/composite/menuiterator/MenuItem.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class MenuItem extends MenuComponent { 4 | String name; 5 | String description; 6 | boolean vegetarian; 7 | double price; 8 | 9 | public MenuItem(String name, 10 | String description, 11 | boolean vegetarian, 12 | double price) { 13 | this.name = name; 14 | this.description = description; 15 | this.vegetarian = vegetarian; 16 | this.price = price; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public String getDescription() { 24 | return description; 25 | } 26 | 27 | public boolean isVegetarian() { 28 | return vegetarian; 29 | } 30 | 31 | public double getPrice() { 32 | return price; 33 | } 34 | 35 | public Iterator createIterator() { 36 | return new NullIterator(); 37 | } 38 | 39 | public void print() { 40 | System.out.print(" " + getName()); 41 | if (isVegetarian()) { 42 | System.out.println("(v)"); 43 | } 44 | System.out.println(", " + getPrice()); 45 | System.out.println(" -- " + getDescription()); 46 | } 47 | } -------------------------------------------------------------------------------- /java/composite/menuiterator/NullIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class NullIterator implements Iterator { 4 | 5 | public Object next() { 6 | return null; 7 | } 8 | 9 | public boolean hasNext() { 10 | return false; 11 | } 12 | 13 | public void remove() { 14 | throw new UnsupportedOperationException(); 15 | } 16 | } -------------------------------------------------------------------------------- /java/composite/menuiterator/Waitress.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class Waitress { 4 | MenuComponent allMenus; 5 | 6 | public Waitress(MenuComponent allMenus) { 7 | this.allMenus = allMenus; 8 | } 9 | 10 | public void printMenu() { 11 | allMenus.print(); 12 | } 13 | 14 | public void printVegetarianMenu() { 15 | Iterator iterator = allMenus.createIterator(); 16 | 17 | System.out.println("\nVEGETARIAN MENU\n----"); 18 | while (iterator.hasNext()) { 19 | MenuComponent menuComponent = 20 | (MenuComponent)iterator.next(); 21 | try { 22 | if (menuComponent.isVegetarian()) { 23 | menuComponent.print(); 24 | } 25 | } catch (UnsupportedOperationException e) {} 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/compound/combined/djview/BPMObserver.java: -------------------------------------------------------------------------------- 1 | public interface BPMObserver { 2 | void updateBPM(); 3 | } -------------------------------------------------------------------------------- /java/compound/combined/djview/BeatBar.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | import javax.swing.*; 4 | 5 | public class BeatBar extends JProgressBar implements Runnable { 6 | JProgressBar progressBar; 7 | Thread thread; 8 | 9 | public BeatBar() { 10 | thread = new Thread(this); 11 | setMaximum(100); 12 | thread.start(); 13 | } 14 | 15 | public void run() { 16 | for(;;) { 17 | int value = getValue(); 18 | value = (int)(value * .75); 19 | setValue(value); 20 | repaint(); 21 | try { 22 | Thread.sleep(50); 23 | } catch (Exception e) {}; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/compound/combined/djview/BeatController.java: -------------------------------------------------------------------------------- 1 | public class BeatController implements ControllerInterface { 2 | BeatModelInterface model; 3 | DJView view; 4 | 5 | public BeatController(BeatModelInterface model) { 6 | this.model = model; 7 | view = new DJView(this, model); 8 | view.createView(); 9 | view.createControls(); 10 | view.disableStopMenuItem(); 11 | view.enableStartMenuItem(); 12 | model.initialize(); 13 | } 14 | 15 | public void start() { 16 | model.on(); 17 | view.disableStartMenuItem(); 18 | view.enableStopMenuItem(); 19 | } 20 | 21 | public void stop() { 22 | model.off(); 23 | view.disableStopMenuItem(); 24 | view.enableStartMenuItem(); 25 | } 26 | 27 | public void increaseBPM() { 28 | int bpm = model.getBPM(); 29 | model.setBPM(bpm + 1); 30 | } 31 | 32 | public void decreaseBPM() { 33 | int bpm = model.getBPM(); 34 | model.setBPM(bpm - 1); 35 | } 36 | 37 | public void setBPM(int bpm) { 38 | model.setBPM(bpm); 39 | } 40 | } -------------------------------------------------------------------------------- /java/compound/combined/djview/BeatModelInterface.java: -------------------------------------------------------------------------------- 1 | public interface BeatModelInterface { 2 | void initialize(); 3 | void on(); 4 | void off(); 5 | void setBPM(int BPM); 6 | int getBPM(); 7 | void registerObserver(BeatObserver o); 8 | void removeObserver(BeatObserver o); 9 | void registerObserver(BPMObserver o); 10 | void removeObserver(BPMObserver o); 11 | } -------------------------------------------------------------------------------- /java/compound/combined/djview/BeatObserver.java: -------------------------------------------------------------------------------- 1 | public interface BeatObserver { 2 | void updateBeat(); 3 | } -------------------------------------------------------------------------------- /java/compound/combined/djview/ControllerInterface.java: -------------------------------------------------------------------------------- 1 | public interface ControllerInterface { 2 | void start(); 3 | void stop(); 4 | void increaseBPM(); 5 | void decreaseBPM(); 6 | void setBPM(int bpm); 7 | } -------------------------------------------------------------------------------- /java/compound/combined/djview/DJTestDrive.java: -------------------------------------------------------------------------------- 1 | public class DJTestDrive { 2 | 3 | public static void main (String[] args) { 4 | BeatModelInterface model = new BeatModel(); 5 | ControllerInterface controller = new BeatController(model); 6 | } 7 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/DuckCall.java: -------------------------------------------------------------------------------- 1 | public class DuckCall implements Quackable { 2 | public void quack() { 3 | System.out.println("Kwak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | public class DuckSimulator { 2 | public static void main(String[] args) { 3 | DuckSimulator simulator = new DuckSimulator(); 4 | simulator.simulate(); 5 | } 6 | 7 | void simulate() { 8 | Quackable mallardDuck = new MallardDuck(); 9 | Quackable redheadDuck = new RedheadDuck(); 10 | Quackable duckCall = new DuckCall(); 11 | Quackable rubberDuck = new RubberDuck(); 12 | Quackable gooseDuck = new GooseAdapter(new Goose()); 13 | 14 | System.out.println("\nDuck Simulator"); 15 | 16 | simulate(mallardDuck); 17 | simulate(redheadDuck); 18 | simulate(duckCall); 19 | simulate(rubberDuck); 20 | simulate(gooseDuck); 21 | } 22 | 23 | void simulate(Quackable duck) { 24 | duck.quack(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/compound/combining/adapter/Goose.java: -------------------------------------------------------------------------------- 1 | public class Goose { 2 | public void honk() { 3 | System.out.println("Honk"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | public class GooseAdapter implements Quackable { 2 | Goose goose; 3 | 4 | public GooseAdapter(Goose goose) { 5 | this.goose = goose; 6 | } 7 | 8 | public void quack() { 9 | goose.honk(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/Quackable.java: -------------------------------------------------------------------------------- 1 | public interface Quackable { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | public class RedheadDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/adapter/RubberDuck.java: -------------------------------------------------------------------------------- 1 | public class RubberDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Squeak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/AbstractDuckFactory.java: -------------------------------------------------------------------------------- 1 | public abstract class AbstractDuckFactory { 2 | public abstract Quackable createMallardDuck(); 3 | public abstract Quackable createRedheadDuck(); 4 | public abstract Quackable createDuckCall(); 5 | public abstract Quackable createRubberDuck(); 6 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/CountingDuckFactory.java: -------------------------------------------------------------------------------- 1 | public class CountingDuckFactory extends AbstractDuckFactory { 2 | 3 | public Quackable createMallardDuck() { 4 | return new QuackCounter(new MallardDuck()); 5 | } 6 | 7 | public Quackable createRedheadDuck() { 8 | return new QuackCounter(new RedheadDuck()); 9 | } 10 | 11 | public Quackable createDuckCall() { 12 | return new QuackCounter(new DuckCall()); 13 | } 14 | 15 | public Quackable createRubberDuck() { 16 | return new QuackCounter(new RubberDuck()); 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/DuckCall.java: -------------------------------------------------------------------------------- 1 | public class DuckCall implements Quackable { 2 | public void quack() { 3 | System.out.println("Kwak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/DuckFactory.java: -------------------------------------------------------------------------------- 1 | public class DuckFactory extends AbstractDuckFactory { 2 | 3 | public Quackable createMallardDuck() { 4 | return new MallardDuck(); 5 | } 6 | 7 | public Quackable createRedheadDuck() { 8 | return new RedheadDuck(); 9 | } 10 | 11 | public Quackable createDuckCall() { 12 | return new DuckCall(); 13 | } 14 | 15 | public Quackable createRubberDuck() { 16 | return new RubberDuck(); 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | public class DuckSimulator { 2 | public static void main(String[] args) { 3 | DuckSimulator simulator = new DuckSimulator(); 4 | AbstractDuckFactory duckFactory = new CountingDuckFactory(); 5 | simulator.simulate(duckFactory); 6 | } 7 | 8 | void simulate(AbstractDuckFactory duckFactory) { 9 | Quackable redheadDuck = duckFactory.createRedheadDuck(); 10 | Quackable duckCall = duckFactory.createDuckCall(); 11 | Quackable rubberDuck = duckFactory.createRubberDuck(); 12 | Quackable gooseDuck = new GooseAdapter(new Goose()); 13 | 14 | System.out.println("\nDuck Simulator: With Composite - Flocks"); 15 | 16 | Flock flockOfDucks = new Flock(); 17 | flockOfDucks.add(redheadDuck); 18 | flockOfDucks.add(duckCall); 19 | flockOfDucks.add(rubberDuck); 20 | flockOfDucks.add(gooseDuck); 21 | 22 | Quackable mallardOne = duckFactory.createMallardDuck(); 23 | Quackable mallardTwo = duckFactory.createMallardDuck(); 24 | Quackable mallardThree = duckFactory.createMallardDuck(); 25 | Quackable mallardFour = duckFactory.createMallardDuck(); 26 | 27 | Flock flockOfMallards = new Flock(); 28 | flockOfMallards.add(mallardOne); 29 | flockOfMallards.add(mallardTwo); 30 | flockOfMallards.add(mallardThree); 31 | flockOfMallards.add(mallardFour); 32 | 33 | flockOfDucks.add(flockOfMallards); 34 | 35 | System.out.println("\nDuck Simulator: Whole Flock Simulation"); 36 | simulate(flockOfDucks); 37 | 38 | System.out.println("\nDuck Simulator: Mallard Flock Simulation"); 39 | simulate(flockOfMallards); 40 | 41 | System.out.println("The ducks quacked " + QuackCounter.getQuacks() + " times"); 42 | } 43 | 44 | void simulate(Quackable duck) { 45 | duck.quack(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /java/compound/combining/composite/Flock.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Flock implements Quackable { 5 | ArrayList quackers = new ArrayList(); 6 | 7 | public void add(Quackable quacker) { 8 | quackers.add(quacker); 9 | } 10 | 11 | public void quack() { 12 | Iterator iterator = quackers.iterator(); 13 | while (iterator.hasNext()) { 14 | Quackable quacker = (Quackable)iterator.next(); 15 | quacker.quack(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/Goose.java: -------------------------------------------------------------------------------- 1 | public class Goose { 2 | public void honk() { 3 | System.out.println("Honk"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | public class GooseAdapter implements Quackable { 2 | Goose goose; 3 | 4 | public GooseAdapter(Goose goose) { 5 | this.goose = goose; 6 | } 7 | 8 | public void quack() { 9 | goose.honk(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/QuackCounter.java: -------------------------------------------------------------------------------- 1 | public class QuackCounter implements Quackable { 2 | Quackable duck; 3 | static int numberOfQuacks; 4 | 5 | public QuackCounter(Quackable duck) { 6 | this.duck = duck; 7 | } 8 | 9 | public void quack() { 10 | duck.quack(); 11 | numberOfQuacks++; 12 | } 13 | 14 | public static int getQuacks() { 15 | return numberOfQuacks; 16 | } 17 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/Quackable.java: -------------------------------------------------------------------------------- 1 | public interface Quackable { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | public class RedheadDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/composite/RubberDuck.java: -------------------------------------------------------------------------------- 1 | public class RubberDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Squeak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/DuckCall.java: -------------------------------------------------------------------------------- 1 | public class DuckCall implements Quackable { 2 | public void quack() { 3 | System.out.println("Kwak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | public class DuckSimulator { 2 | public static void main(String[] args) { 3 | DuckSimulator simulator = new DuckSimulator(); 4 | simulator.simulate(); 5 | } 6 | 7 | void simulate() { 8 | Quackable mallardDuck = new QuackCounter(new MallardDuck()); 9 | Quackable redheadDuck = new QuackCounter(new RedheadDuck()); 10 | Quackable duckCall = new QuackCounter(new DuckCall()); 11 | Quackable rubberDuck = new QuackCounter(new RubberDuck()); 12 | Quackable gooseDuck = new GooseAdapter(new Goose()); 13 | 14 | System.out.println("\nDuck Simulator"); 15 | 16 | simulate(mallardDuck); 17 | simulate(redheadDuck); 18 | simulate(duckCall); 19 | simulate(rubberDuck); 20 | simulate(gooseDuck); 21 | 22 | System.out.println("The ducks quacked " + QuackCounter.getQuacks() + " times"); 23 | } 24 | 25 | void simulate(Quackable duck) { 26 | duck.quack(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/compound/combining/decorator/Goose.java: -------------------------------------------------------------------------------- 1 | public class Goose { 2 | public void honk() { 3 | System.out.println("Honk"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | public class GooseAdapter implements Quackable { 2 | Goose goose; 3 | 4 | public GooseAdapter(Goose goose) { 5 | this.goose = goose; 6 | } 7 | 8 | public void quack() { 9 | goose.honk(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/QuackCounter.java: -------------------------------------------------------------------------------- 1 | public class QuackCounter implements Quackable { 2 | Quackable duck; 3 | static int numberOfQuacks; 4 | 5 | public QuackCounter(Quackable duck) { 6 | this.duck = duck; 7 | } 8 | 9 | public void quack() { 10 | duck.quack(); 11 | numberOfQuacks++; 12 | } 13 | 14 | public static int getQuacks() { 15 | return numberOfQuacks; 16 | } 17 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/Quackable.java: -------------------------------------------------------------------------------- 1 | public interface Quackable { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | public class RedheadDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/decorator/RubberDuck.java: -------------------------------------------------------------------------------- 1 | public class RubberDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Squeak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/ducks/DuckCall.java: -------------------------------------------------------------------------------- 1 | public class DuckCall implements Quackable { 2 | public void quack() { 3 | System.out.println("Kwak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/ducks/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | public class DuckSimulator { 2 | public static void main(String[] args) { 3 | DuckSimulator simulator = new DuckSimulator(); 4 | simulator.simulate(); 5 | } 6 | 7 | void simulate() { 8 | Quackable mallardDuck = new MallardDuck(); 9 | Quackable redheadDuck = new RedheadDuck(); 10 | Quackable duckCall = new DuckCall(); 11 | Quackable rubberDuck = new RubberDuck(); 12 | 13 | System.out.println("\nDuck Simulator"); 14 | 15 | simulate(mallardDuck); 16 | simulate(redheadDuck); 17 | simulate(duckCall); 18 | simulate(rubberDuck); 19 | } 20 | 21 | void simulate(Quackable duck) { 22 | duck.quack(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /java/compound/combining/ducks/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/ducks/Quackable.java: -------------------------------------------------------------------------------- 1 | public interface Quackable { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/ducks/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | public class RedheadDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/ducks/RubberDuck.java: -------------------------------------------------------------------------------- 1 | public class RubberDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Squeak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/AbstractDuckFactory.java: -------------------------------------------------------------------------------- 1 | public abstract class AbstractDuckFactory { 2 | public abstract Quackable createMallardDuck(); 3 | public abstract Quackable createRedheadDuck(); 4 | public abstract Quackable createDuckCall(); 5 | public abstract Quackable createRubberDuck(); 6 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/CountingDuckFactory.java: -------------------------------------------------------------------------------- 1 | public class CountingDuckFactory extends AbstractDuckFactory { 2 | 3 | public Quackable createMallardDuck() { 4 | return new QuackCounter(new MallardDuck()); 5 | } 6 | 7 | public Quackable createRedheadDuck() { 8 | return new QuackCounter(new RedheadDuck()); 9 | } 10 | 11 | public Quackable createDuckCall() { 12 | return new QuackCounter(new DuckCall()); 13 | } 14 | 15 | public Quackable createRubberDuck() { 16 | return new QuackCounter(new RubberDuck()); 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/DuckCall.java: -------------------------------------------------------------------------------- 1 | public class DuckCall implements Quackable { 2 | public void quack() { 3 | System.out.println("Kwak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/DuckFactory.java: -------------------------------------------------------------------------------- 1 | public class DuckFactory extends AbstractDuckFactory { 2 | 3 | public Quackable createMallardDuck() { 4 | return new MallardDuck(); 5 | } 6 | 7 | public Quackable createRedheadDuck() { 8 | return new RedheadDuck(); 9 | } 10 | 11 | public Quackable createDuckCall() { 12 | return new DuckCall(); 13 | } 14 | 15 | public Quackable createRubberDuck() { 16 | return new RubberDuck(); 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | public class DuckSimulator { 2 | public static void main(String[] args) { 3 | DuckSimulator simulator = new DuckSimulator(); 4 | AbstractDuckFactory duckFactory = new CountingDuckFactory(); 5 | simulator.simulate(duckFactory); 6 | } 7 | 8 | void simulate(AbstractDuckFactory duckFactory) { 9 | Quackable mallardDuck = duckFactory.createMallardDuck(); 10 | Quackable redheadDuck = duckFactory.createRedheadDuck(); 11 | Quackable duckCall = duckFactory.createDuckCall(); 12 | Quackable rubberDuck = duckFactory.createRubberDuck(); 13 | Quackable gooseDuck = new GooseAdapter(new Goose()); 14 | 15 | System.out.println("\nDuck Simulator"); 16 | 17 | simulate(mallardDuck); 18 | simulate(redheadDuck); 19 | simulate(duckCall); 20 | simulate(rubberDuck); 21 | simulate(gooseDuck); 22 | 23 | System.out.println("The ducks quacked " + QuackCounter.getQuacks() + " times"); 24 | } 25 | 26 | void simulate(Quackable duck) { 27 | duck.quack(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/compound/combining/factory/Goose.java: -------------------------------------------------------------------------------- 1 | public class Goose { 2 | public void honk() { 3 | System.out.println("Honk"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | public class GooseAdapter implements Quackable { 2 | Goose goose; 3 | 4 | public GooseAdapter(Goose goose) { 5 | this.goose = goose; 6 | } 7 | 8 | public void quack() { 9 | goose.honk(); 10 | } 11 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/QuackCounter.java: -------------------------------------------------------------------------------- 1 | public class QuackCounter implements Quackable { 2 | Quackable duck; 3 | static int numberOfQuacks; 4 | 5 | public QuackCounter(Quackable duck) { 6 | this.duck = duck; 7 | } 8 | 9 | public void quack() { 10 | duck.quack(); 11 | numberOfQuacks++; 12 | } 13 | 14 | public static int getQuacks() { 15 | return numberOfQuacks; 16 | } 17 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/Quackable.java: -------------------------------------------------------------------------------- 1 | public interface Quackable { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | public class RedheadDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/factory/RubberDuck.java: -------------------------------------------------------------------------------- 1 | public class RubberDuck implements Quackable { 2 | public void quack() { 3 | System.out.println("Squeak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/AbstractDuckFactory.java: -------------------------------------------------------------------------------- 1 | public abstract class AbstractDuckFactory { 2 | public abstract Quackable createMallardDuck(); 3 | public abstract Quackable createRedheadDuck(); 4 | public abstract Quackable createDuckCall(); 5 | public abstract Quackable createRubberDuck(); 6 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/CountingDuckFactory.java: -------------------------------------------------------------------------------- 1 | public class CountingDuckFactory extends AbstractDuckFactory { 2 | 3 | public Quackable createMallardDuck() { 4 | return new QuackCounter(new MallardDuck()); 5 | } 6 | 7 | public Quackable createRedheadDuck() { 8 | return new QuackCounter(new RedheadDuck()); 9 | } 10 | 11 | public Quackable createDuckCall() { 12 | return new QuackCounter(new DuckCall()); 13 | } 14 | 15 | public Quackable createRubberDuck() { 16 | return new QuackCounter(new RubberDuck()); 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/DuckCall.java: -------------------------------------------------------------------------------- 1 | public class DuckCall implements Quackable { 2 | Observable observable; 3 | 4 | public DuckCall() { 5 | observable = new Observable(this); 6 | } 7 | 8 | public void quack() { 9 | System.out.println("Kwak"); 10 | notifyObservers(); 11 | } 12 | 13 | public void registerObserver(Observer observer) { 14 | observable.registerObserver(observer); 15 | } 16 | 17 | public void notifyObservers() { 18 | observable.notifyObservers(); 19 | } 20 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/DuckFactory.java: -------------------------------------------------------------------------------- 1 | public class DuckFactory extends AbstractDuckFactory { 2 | 3 | public Quackable createMallardDuck() { 4 | return new MallardDuck(); 5 | } 6 | 7 | public Quackable createRedheadDuck() { 8 | return new RedheadDuck(); 9 | } 10 | 11 | public Quackable createDuckCall() { 12 | return new DuckCall(); 13 | } 14 | 15 | public Quackable createRubberDuck() { 16 | return new RubberDuck(); 17 | } 18 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/Flock.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Flock implements Quackable { 5 | ArrayList quackers = new ArrayList(); 6 | 7 | public void add(Quackable quacker) { 8 | quackers.add(quacker); 9 | } 10 | 11 | public void quack() { 12 | Iterator iterator = quackers.iterator(); 13 | while (iterator.hasNext()) { 14 | Quackable quacker = (Quackable)iterator.next(); 15 | quacker.quack(); 16 | } 17 | } 18 | 19 | public void registerObserver(Observer observer) { 20 | Iterator iterator = quackers.iterator(); 21 | while (iterator.hasNext()) { 22 | Quackable quacker = (Quackable)iterator.next(); 23 | quacker.registerObserver(observer); 24 | } 25 | } 26 | 27 | public void notifyObservers() { } 28 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/Goose.java: -------------------------------------------------------------------------------- 1 | public class Goose { 2 | public void honk() { 3 | System.out.println("Honk"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | public class GooseAdapter implements Quackable { 2 | Goose goose; 3 | Observable observable; 4 | 5 | public GooseAdapter(Goose goose) { 6 | this.goose = goose; 7 | observable = new Observable(this); 8 | } 9 | 10 | public void quack() { 11 | goose.honk(); 12 | notifyObservers(); 13 | } 14 | 15 | public void registerObserver(Observer observer) { 16 | observable.registerObserver(observer); 17 | } 18 | 19 | public void notifyObservers() { 20 | observable.notifyObservers(); 21 | } 22 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck implements Quackable { 2 | Observable observable; 3 | 4 | public MallardDuck() { 5 | observable = new Observable(this); 6 | } 7 | 8 | public void quack() { 9 | System.out.println("Quack"); 10 | notifyObservers(); 11 | } 12 | 13 | public void registerObserver(Observer observer) { 14 | observable.registerObserver(observer); 15 | } 16 | 17 | public void notifyObservers() { 18 | observable.notifyObservers(); 19 | } 20 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/Observable.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Observable implements QuackObservable { 5 | ArrayList observers = new ArrayList(); 6 | QuackObservable duck; 7 | 8 | public Observable(QuackObservable duck) { 9 | this.duck = duck; 10 | } 11 | 12 | public void registerObserver(Observer observer) { 13 | observers.add(observer); 14 | } 15 | 16 | public void notifyObservers() { 17 | Iterator iterator = observers.iterator(); 18 | while (iterator.hasNext()) { 19 | Observer observer = (Observer)iterator.next(); 20 | observer.update(duck); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/Observer.java: -------------------------------------------------------------------------------- 1 | public interface Observer { 2 | public void update(QuackObservable duck); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/QuackCounter.java: -------------------------------------------------------------------------------- 1 | public class QuackCounter implements Quackable { 2 | Quackable duck; 3 | static int numberOfQuacks; 4 | 5 | public QuackCounter(Quackable duck) { 6 | this.duck = duck; 7 | } 8 | 9 | public void quack() { 10 | duck.quack(); 11 | numberOfQuacks++; 12 | } 13 | 14 | public static int getQuacks() { 15 | return numberOfQuacks; 16 | } 17 | 18 | public void registerObserver(Observer observer) { 19 | duck.registerObserver(observer); 20 | } 21 | 22 | public void notifyObservers() { 23 | duck.notifyObservers(); 24 | } 25 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/QuackObservable.java: -------------------------------------------------------------------------------- 1 | public interface QuackObservable { 2 | public void registerObserver(Observer observer); 3 | public void notifyObservers(); 4 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/Quackable.java: -------------------------------------------------------------------------------- 1 | public interface Quackable extends QuackObservable { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/Quackologist.java: -------------------------------------------------------------------------------- 1 | public class Quackologist implements Observer { 2 | 3 | public void update(QuackObservable duck) { 4 | System.out.println("Quackologist: " + duck + " just quacked."); 5 | } 6 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | public class RedheadDuck implements Quackable { 2 | Observable observable; 3 | 4 | public RedheadDuck() { 5 | observable = new Observable(this); 6 | } 7 | public void quack() { 8 | System.out.println("Quack"); 9 | notifyObservers(); 10 | } 11 | 12 | public void registerObserver(Observer observer) { 13 | observable.registerObserver(observer); 14 | } 15 | 16 | public void notifyObservers() { 17 | observable.notifyObservers(); 18 | } 19 | } -------------------------------------------------------------------------------- /java/compound/combining/observer/RubberDuck.java: -------------------------------------------------------------------------------- 1 | public class RubberDuck implements Quackable { 2 | Observable observable; 3 | 4 | public RubberDuck() { 5 | observable = new Observable(this); 6 | } 7 | 8 | public void quack() { 9 | System.out.println("Squeak"); 10 | notifyObservers(); 11 | } 12 | 13 | public void registerObserver(Observer observer) { 14 | observable.registerObserver(observer); 15 | } 16 | 17 | public void notifyObservers() { 18 | observable.notifyObservers(); 19 | } 20 | } -------------------------------------------------------------------------------- /java/decorator/io/InputTest.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class InputTest { 4 | public static void main(String[] args) throws IOException { 5 | int c; 6 | 7 | try { 8 | InputStream in = 9 | new LowerCaseInputStream( 10 | new BufferedInputStream( 11 | new FileInputStream("test.txt"))); 12 | 13 | while((c = in.read()) >= 0) { 14 | System.out.print((char)c); 15 | } 16 | 17 | in.close(); 18 | } catch (IOException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/decorator/io/LowerCaseInputStream.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class LowerCaseInputStream extends FilterInputStream { 4 | 5 | public LowerCaseInputStream(InputStream in) { 6 | super(in); 7 | } 8 | 9 | public int read() throws IOException { 10 | int c = super.read(); 11 | return (c == -1 ? c : Character.toLowerCase((char)c)); 12 | } 13 | 14 | public int read(byte[] b, int offset, int len) throws IOException { 15 | int result = super.read(b, offset, len); 16 | for (int i = offset; i < offset+result; i++) { 17 | b[i] = (byte)Character.toLowerCase((char)b[i]); 18 | } 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/decorator/starbuzz/Beverage.java: -------------------------------------------------------------------------------- 1 | public abstract class Beverage { 2 | String description = "Unknown Beverage"; 3 | 4 | public String getDescription() { 5 | return description; 6 | } 7 | 8 | public abstract double cost(); 9 | } 10 | -------------------------------------------------------------------------------- /java/decorator/starbuzz/CondimentDecorator.java: -------------------------------------------------------------------------------- 1 | public abstract class CondimentDecorator extends Beverage { 2 | public abstract String getDescription(); 3 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/DarkRoast.java: -------------------------------------------------------------------------------- 1 | public class DarkRoast extends Beverage { 2 | public DarkRoast() { 3 | description = "Dark Roast Coffee"; 4 | } 5 | 6 | public double cost() { 7 | return .99; 8 | } 9 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/Decaf.java: -------------------------------------------------------------------------------- 1 | public class Decaf extends Beverage { 2 | public Decaf() { 3 | description = "Decaf Coffee"; 4 | } 5 | 6 | public double cost() { 7 | return 1.05; 8 | } 9 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/Espresso.java: -------------------------------------------------------------------------------- 1 | public class Espresso extends Beverage { 2 | public Espresso() { 3 | description = "Espresso"; 4 | } 5 | 6 | public double cost() { 7 | return 1.99; 8 | } 9 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/HouseBlend.java: -------------------------------------------------------------------------------- 1 | public class HouseBlend extends Beverage { 2 | public HouseBlend() { 3 | description = "House Blend Coffee"; 4 | } 5 | 6 | public double cost() { 7 | return .89; 8 | } 9 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/Mocha.java: -------------------------------------------------------------------------------- 1 | public class Mocha extends CondimentDecorator { 2 | Beverage beverage; 3 | 4 | public Mocha(Beverage beverage) { 5 | this.beverage = beverage; 6 | } 7 | 8 | public String getDescription() { 9 | return beverage.getDescription() + ", Mocha"; 10 | } 11 | 12 | public double cost() { 13 | return beverage.cost() + .20; 14 | } 15 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/Soy.java: -------------------------------------------------------------------------------- 1 | public class Soy extends CondimentDecorator { 2 | Beverage beverage; 3 | 4 | public Soy(Beverage beverage) { 5 | this.beverage = beverage; 6 | } 7 | 8 | public String getDescription() { 9 | return beverage.getDescription() + ", Soy"; 10 | } 11 | 12 | public double cost() { 13 | return beverage.cost() + .15; 14 | } 15 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/StarbuzzCoffee.java: -------------------------------------------------------------------------------- 1 | public class StarbuzzCoffee { 2 | 3 | public static void main(String[] args) { 4 | Beverage beverage = new Espresso(); 5 | printBeverage(beverage); 6 | 7 | Beverage beverage2 = new DarkRoast(); // Make a Dark Roast object. 8 | beverage2 = new Mocha(beverage2); // Wrap it with a Mocha. 9 | beverage2 = new Mocha(beverage2); // Wrap it in a second Mocha. 10 | beverage2 = new Whip(beverage2); // Wrap it in a Whip. 11 | printBeverage(beverage2); 12 | 13 | Beverage beverage3 = new HouseBlend(); 14 | beverage3 = new Soy(beverage3); 15 | beverage3 = new Mocha(beverage3); 16 | beverage3 = new Whip(beverage3); 17 | printBeverage(beverage3); 18 | } 19 | 20 | public static void printBeverage(Beverage beverage) { 21 | System.out.println(beverage.getDescription() + " $" + beverage.cost()); 22 | } 23 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/SteamedMilk.java: -------------------------------------------------------------------------------- 1 | public class SteamedMilk extends CondimentDecorator { 2 | Beverage beverage; 3 | 4 | public SteamedMilk(Beverage beverage) { 5 | this.beverage = beverage; 6 | } 7 | 8 | public String getDescription() { 9 | return beverage.getDescription() + ", Steamed Milk"; 10 | } 11 | 12 | public double cost() { 13 | return beverage.cost() + .10; 14 | } 15 | } -------------------------------------------------------------------------------- /java/decorator/starbuzz/Whip.java: -------------------------------------------------------------------------------- 1 | public class Whip extends CondimentDecorator { 2 | Beverage beverage; 3 | 4 | public Whip (Beverage beverage) { 5 | this.beverage = beverage; 6 | } 7 | 8 | public String getDescription() { 9 | return beverage.getDescription() + ", Whip"; 10 | } 11 | 12 | public double cost() { 13 | return beverage.cost() + .10; 14 | } 15 | } -------------------------------------------------------------------------------- /java/facade/hometheater/Amplifier.java: -------------------------------------------------------------------------------- 1 | public class Amplifier { 2 | String description; 3 | Tuner tuner; 4 | DvdPlayer dvd; 5 | CdPlayer cd; 6 | int volume; 7 | 8 | public Amplifier(String description) { 9 | this.description = description; 10 | } 11 | 12 | public void on() { 13 | System.out.println(description + " is On"); 14 | } 15 | 16 | public void off() { 17 | System.out.println(description + " is Off"); 18 | } 19 | 20 | public void setSurroundSound() { 21 | System.out.println(description + " Surround Sound enabled"); 22 | } 23 | 24 | public void setStereoSound() { 25 | System.out.println(description + " Stereo Mode enabled"); 26 | } 27 | 28 | public void setTuner(Tuner tuner) { 29 | this.tuner = tuner; 30 | } 31 | 32 | public void setDvd(DvdPlayer dvd) { 33 | this.dvd = dvd; 34 | } 35 | 36 | public void setCd(CdPlayer cd) { 37 | this.cd = cd; 38 | } 39 | 40 | public void setVolume(int volume) { 41 | this.volume = volume; 42 | } 43 | } -------------------------------------------------------------------------------- /java/facade/hometheater/CdPlayer.java: -------------------------------------------------------------------------------- 1 | public class CdPlayer { 2 | String description; 3 | int currentTrack; 4 | Amplifier amplifier; 5 | String title; 6 | 7 | public CdPlayer(String description, Amplifier amplifier) { 8 | this.description = description; 9 | this.amplifier = amplifier; 10 | } 11 | 12 | public void on() { 13 | System.out.println(description + " on"); 14 | } 15 | 16 | public void off() { 17 | System.out.println(description + " off"); 18 | } 19 | 20 | public void eject() { 21 | title = null; 22 | System.out.println(description + " eject"); 23 | } 24 | 25 | public void play(String title) { 26 | this.title = title; 27 | currentTrack = 0; 28 | System.out.println(description + " playing \"" + title + "\""); 29 | } 30 | 31 | public void play(int track) { 32 | if (title == null) { 33 | System.out.println(description + " can't play track " + currentTrack + 34 | ", no cd inserted"); 35 | } else { 36 | currentTrack = track; 37 | System.out.println(description + " playing track " + currentTrack); 38 | } 39 | } 40 | 41 | public void stop() { 42 | currentTrack = 0; 43 | System.out.println(description + " stopped"); 44 | } 45 | 46 | public void pause() { 47 | System.out.println(description + " paused \"" + title + "\""); 48 | } 49 | 50 | public String toString() { 51 | return description; 52 | } 53 | } -------------------------------------------------------------------------------- /java/facade/hometheater/DvdPlayer.java: -------------------------------------------------------------------------------- 1 | public class DvdPlayer { 2 | String description; 3 | int currentTrack; 4 | Amplifier amplifier; 5 | String movie; 6 | 7 | public DvdPlayer(String description, Amplifier amplifier) { 8 | this.description = description; 9 | this.amplifier = amplifier; 10 | } 11 | 12 | public void on() { 13 | System.out.println(description + " on"); 14 | } 15 | 16 | public void off() { 17 | System.out.println(description + " off"); 18 | } 19 | 20 | public void eject() { 21 | movie = null; 22 | System.out.println(description + " eject"); 23 | } 24 | 25 | public void play(String movie) { 26 | this.movie = movie; 27 | currentTrack = 0; 28 | System.out.println(description + " playing \"" + movie + "\""); 29 | } 30 | 31 | public void play(int track) { 32 | if (movie == null) { 33 | System.out.println(description + " can't play track " + track + " no dvd inserted"); 34 | } else { 35 | currentTrack = track; 36 | System.out.println(description + " playing track " + currentTrack + " of \"" + movie + "\""); 37 | } 38 | } 39 | 40 | public void stop() { 41 | currentTrack = 0; 42 | System.out.println(description + " stopped \"" + movie + "\""); 43 | } 44 | 45 | public void pause() { 46 | System.out.println(description + " paused \"" + movie + "\""); 47 | } 48 | 49 | public void setTwoChannelAudio() { 50 | System.out.println(description + " set two channel audio"); 51 | } 52 | 53 | public void setSurroundAudio() { 54 | System.out.println(description + " set surround audio"); 55 | } 56 | 57 | public String toString() { 58 | return description; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /java/facade/hometheater/HomeTheaterTestDrive.java: -------------------------------------------------------------------------------- 1 | public class HomeTheaterTestDrive { 2 | 3 | public static void main(String[] args) { 4 | Amplifier amp = new Amplifier("Top-O-Line Amplifier"); 5 | Tuner tuner = new Tuner("Top-O-Line AM/FM Tuner", amp); 6 | DvdPlayer dvd = new DvdPlayer("Top-O-Line DVD Player", amp); 7 | CdPlayer cd = new CdPlayer("Top-O-Line CD Player", amp); 8 | Projector projector = new Projector("Top-O-Line Projector", dvd); 9 | TheaterLights lights = new TheaterLights("Theater Ceiling Lights"); 10 | Screen screen = new Screen("Theater Screen"); 11 | PopcornPopper popper = new PopcornPopper("Popcorn Popper"); 12 | 13 | HomeTheaterFacade homeTheater = 14 | new HomeTheaterFacade(amp, tuner, dvd, cd, 15 | projector, screen, lights, popper); 16 | 17 | homeTheater.watchMovie("Raiders of the Lost Ark"); 18 | System.out.println("\n"); 19 | homeTheater.endMovie(); 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /java/facade/hometheater/PopcornPopper.java: -------------------------------------------------------------------------------- 1 | public class PopcornPopper { 2 | String description; 3 | 4 | public PopcornPopper(String description) { 5 | this.description = description; 6 | } 7 | 8 | public void on() { 9 | System.out.println(description + " On"); 10 | } 11 | 12 | public void off() { 13 | System.out.println(description + " Off"); 14 | } 15 | 16 | public void pop() { 17 | System.out.println(description + " popping popcorn!"); 18 | } 19 | 20 | public String toString() { 21 | return description; 22 | } 23 | } -------------------------------------------------------------------------------- /java/facade/hometheater/Projector.java: -------------------------------------------------------------------------------- 1 | public class Projector { 2 | String description; 3 | DvdPlayer dvdPlayer; 4 | 5 | public Projector(String description, DvdPlayer dvdPlayer) { 6 | this.description = description; 7 | this.dvdPlayer = dvdPlayer; 8 | } 9 | 10 | public void on() { 11 | System.out.println(description + " On"); 12 | } 13 | 14 | public void off() { 15 | System.out.println(description + " Off"); 16 | } 17 | 18 | public void wideScreenMode() { 19 | System.out.println(description + " in Widescreen Mode (16x9 Aspect Ratio)"); 20 | } 21 | 22 | public void tvMode() { 23 | System.out.println(description + " in TV Mode (4x3 Aspect Ratio)"); 24 | } 25 | 26 | public String toString() { 27 | return description; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/facade/hometheater/Screen.java: -------------------------------------------------------------------------------- 1 | public class Screen { 2 | String description; 3 | 4 | public Screen(String description) { 5 | this.description = description; 6 | } 7 | 8 | public void up() { 9 | System.out.println(description + " going up"); 10 | } 11 | 12 | public void down() { 13 | System.out.println(description + " going down"); 14 | } 15 | 16 | public String toString() { 17 | return description; 18 | } 19 | } -------------------------------------------------------------------------------- /java/facade/hometheater/TheaterLights.java: -------------------------------------------------------------------------------- 1 | public class TheaterLights { 2 | String description; 3 | 4 | public TheaterLights(String description) { 5 | this.description = description; 6 | } 7 | 8 | public void on() { 9 | System.out.println(description + " on"); 10 | } 11 | 12 | public void off() { 13 | System.out.println(description + " off"); 14 | } 15 | 16 | public void dim(int level) { 17 | System.out.println(description + " dimming to " + level + "%"); 18 | } 19 | 20 | public String toString() { 21 | return description; 22 | } 23 | } -------------------------------------------------------------------------------- /java/facade/hometheater/Tuner.java: -------------------------------------------------------------------------------- 1 | public class Tuner { 2 | String description; 3 | Amplifier amplifier; 4 | double frequency; 5 | 6 | public Tuner(String description, Amplifier amplifier) { 7 | this.description = description; 8 | } 9 | 10 | public void on() { 11 | System.out.println(description + " on"); 12 | } 13 | 14 | public void off() { 15 | System.out.println(description + " off"); 16 | } 17 | 18 | public void setFrequency(double frequency) { 19 | System.out.println(description + " setting frequency to " + frequency); 20 | this.frequency = frequency; 21 | } 22 | 23 | public void setAm() { 24 | System.out.println(description + " setting AM mode"); 25 | } 26 | 27 | public void setFm() { 28 | System.out.println(description + " setting FM mode"); 29 | } 30 | 31 | public String toString() { 32 | return description; 33 | } 34 | } -------------------------------------------------------------------------------- /java/factory/pizzaaf/BlackOlives.java: -------------------------------------------------------------------------------- 1 | public class BlackOlives implements Veggies { 2 | 3 | public String toString() { 4 | return "Black Olives"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Cheese.java: -------------------------------------------------------------------------------- 1 | public interface Cheese { 2 | public String toString(); 3 | } 4 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/CheesePizza.java: -------------------------------------------------------------------------------- 1 | public class CheesePizza extends Pizza { 2 | PizzaIngredientFactory ingredientFactory; 3 | 4 | public CheesePizza(PizzaIngredientFactory ingredientFactory) { 5 | this.ingredientFactory = ingredientFactory; 6 | } 7 | 8 | void prepare() { 9 | System.out.println("Preparing " + name); 10 | dough = ingredientFactory.createDough(); 11 | sauce = ingredientFactory.createSauce(); 12 | cheese = ingredientFactory.createCheese(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ChicagoPizzaIngredientFactory.java: -------------------------------------------------------------------------------- 1 | public class ChicagoPizzaIngredientFactory implements PizzaIngredientFactory 2 | { 3 | 4 | public Dough createDough() { 5 | return new ThickCrustDough(); 6 | } 7 | 8 | public Sauce createSauce() { 9 | return new PlumTomatoSauce(); 10 | } 11 | 12 | public Cheese createCheese() { 13 | return new MozzarellaCheese(); 14 | } 15 | 16 | public Veggies[] createVeggies() { 17 | Veggies veggies[] = { new BlackOlives(), 18 | new Spinach(), 19 | new Eggplant() }; 20 | return veggies; 21 | } 22 | 23 | public Pepperoni createPepperoni() { 24 | return new SlicedPepperoni(); 25 | } 26 | 27 | public Clams createClam() { 28 | return new FrozenClams(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ChicagoPizzaStore.java: -------------------------------------------------------------------------------- 1 | public class ChicagoPizzaStore extends PizzaStore { 2 | 3 | protected Pizza createPizza(String item) { 4 | Pizza pizza = null; 5 | PizzaIngredientFactory ingredientFactory = 6 | new ChicagoPizzaIngredientFactory(); 7 | 8 | if (item.equals("cheese")) { 9 | 10 | pizza = new CheesePizza(ingredientFactory); 11 | pizza.setName("Chicago Style Cheese Pizza"); 12 | 13 | } else if (item.equals("veggie")) { 14 | 15 | pizza = new VeggiePizza(ingredientFactory); 16 | pizza.setName("Chicago Style Veggie Pizza"); 17 | 18 | } else if (item.equals("clam")) { 19 | 20 | pizza = new ClamPizza(ingredientFactory); 21 | pizza.setName("Chicago Style Clam Pizza"); 22 | 23 | } else if (item.equals("pepperoni")) { 24 | 25 | pizza = new PepperoniPizza(ingredientFactory); 26 | pizza.setName("Chicago Style Pepperoni Pizza"); 27 | 28 | } 29 | return pizza; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ClamPizza.java: -------------------------------------------------------------------------------- 1 | public class ClamPizza extends Pizza { 2 | PizzaIngredientFactory ingredientFactory; 3 | 4 | public ClamPizza(PizzaIngredientFactory ingredientFactory) { 5 | this.ingredientFactory = ingredientFactory; 6 | } 7 | 8 | void prepare() { 9 | System.out.println("Preparing " + name); 10 | dough = ingredientFactory.createDough(); 11 | sauce = ingredientFactory.createSauce(); 12 | cheese = ingredientFactory.createCheese(); 13 | clam = ingredientFactory.createClam(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Clams.java: -------------------------------------------------------------------------------- 1 | public interface Clams { 2 | public String toString(); 3 | } 4 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Dough.java: -------------------------------------------------------------------------------- 1 | public interface Dough { 2 | public String toString(); 3 | } 4 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Eggplant.java: -------------------------------------------------------------------------------- 1 | public class Eggplant implements Veggies { 2 | 3 | public String toString() { 4 | return "Eggplant"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/FreshClams.java: -------------------------------------------------------------------------------- 1 | public class FreshClams implements Clams { 2 | 3 | public String toString() { 4 | return "Fresh Clams from Long Island Sound"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/FrozenClams.java: -------------------------------------------------------------------------------- 1 | public class FrozenClams implements Clams { 2 | 3 | public String toString() { 4 | return "Frozen Clams from Chesapeake Bay"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Garlic.java: -------------------------------------------------------------------------------- 1 | public class Garlic implements Veggies { 2 | 3 | public String toString() { 4 | return "Garlic"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/MarinaraSauce.java: -------------------------------------------------------------------------------- 1 | public class MarinaraSauce implements Sauce { 2 | public String toString() { 3 | return "Marinara Sauce"; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/MozzarellaCheese.java: -------------------------------------------------------------------------------- 1 | public class MozzarellaCheese implements Cheese { 2 | 3 | public String toString() { 4 | return "Shredded Mozzarella"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Mushroom.java: -------------------------------------------------------------------------------- 1 | public class Mushroom implements Veggies { 2 | 3 | public String toString() { 4 | return "Mushrooms"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/NYPizzaIngredientFactory.java: -------------------------------------------------------------------------------- 1 | public class NYPizzaIngredientFactory implements PizzaIngredientFactory { 2 | 3 | public Dough createDough() { 4 | return new ThinCrustDough(); 5 | } 6 | 7 | public Sauce createSauce() { 8 | return new MarinaraSauce(); 9 | } 10 | 11 | public Cheese createCheese() { 12 | return new ReggianoCheese(); 13 | } 14 | 15 | public Veggies[] createVeggies() { 16 | Veggies veggies[] = { new Garlic(), new Onion(), new Mushroom(), new RedPepper() }; 17 | return veggies; 18 | } 19 | 20 | public Pepperoni createPepperoni() { 21 | return new SlicedPepperoni(); 22 | } 23 | 24 | public Clams createClam() { 25 | return new FreshClams(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/NYPizzaStore.java: -------------------------------------------------------------------------------- 1 | public class NYPizzaStore extends PizzaStore { 2 | 3 | protected Pizza createPizza(String item) { 4 | Pizza pizza = null; 5 | PizzaIngredientFactory ingredientFactory = 6 | new NYPizzaIngredientFactory(); 7 | 8 | if (item.equals("cheese")) { 9 | 10 | pizza = new CheesePizza(ingredientFactory); 11 | pizza.setName("New York Style Cheese Pizza"); 12 | 13 | } else if (item.equals("veggie")) { 14 | 15 | pizza = new VeggiePizza(ingredientFactory); 16 | pizza.setName("New York Style Veggie Pizza"); 17 | 18 | } else if (item.equals("clam")) { 19 | 20 | pizza = new ClamPizza(ingredientFactory); 21 | pizza.setName("New York Style Clam Pizza"); 22 | 23 | } else if (item.equals("pepperoni")) { 24 | 25 | pizza = new PepperoniPizza(ingredientFactory); 26 | pizza.setName("New York Style Pepperoni Pizza"); 27 | 28 | } 29 | return pizza; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Onion.java: -------------------------------------------------------------------------------- 1 | public class Onion implements Veggies { 2 | 3 | public String toString() { 4 | return "Onion"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ParmesanCheese.java: -------------------------------------------------------------------------------- 1 | public class ParmesanCheese implements Cheese { 2 | 3 | public String toString() { 4 | return "Shredded Parmesan"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Pepperoni.java: -------------------------------------------------------------------------------- 1 | public interface Pepperoni { 2 | public String toString(); 3 | } 4 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | public class PepperoniPizza extends Pizza { 2 | PizzaIngredientFactory ingredientFactory; 3 | 4 | public PepperoniPizza(PizzaIngredientFactory ingredientFactory) { 5 | this.ingredientFactory = ingredientFactory; 6 | } 7 | 8 | void prepare() { 9 | System.out.println("Preparing " + name); 10 | dough = ingredientFactory.createDough(); 11 | sauce = ingredientFactory.createSauce(); 12 | cheese = ingredientFactory.createCheese(); 13 | veggies = ingredientFactory.createVeggies(); 14 | pepperoni = ingredientFactory.createPepperoni(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Pizza.java: -------------------------------------------------------------------------------- 1 | public abstract class Pizza { 2 | String name; 3 | Dough dough; 4 | Sauce sauce; 5 | Veggies veggies[]; 6 | Cheese cheese; 7 | Pepperoni pepperoni; 8 | Clams clam; 9 | 10 | abstract void prepare(); 11 | 12 | void bake() { 13 | System.out.println("Bake for 25 minutes at 350"); 14 | } 15 | 16 | void cut() { 17 | System.out.println("Cutting the pizza into diagonal slices"); 18 | } 19 | 20 | void box() { 21 | System.out.println("Place pizza in official PizzaStore box"); 22 | } 23 | 24 | void setName(String name) { 25 | this.name = name; 26 | } 27 | 28 | String getName() { 29 | return name; 30 | } 31 | 32 | public String toString() { 33 | StringBuffer result = new StringBuffer(); 34 | result.append("---- " + name + " ----\n"); 35 | if (dough != null) { 36 | result.append(dough); 37 | result.append("\n"); 38 | } 39 | if (sauce != null) { 40 | result.append(sauce); 41 | result.append("\n"); 42 | } 43 | if (cheese != null) { 44 | result.append(cheese); 45 | result.append("\n"); 46 | } 47 | if (veggies != null) { 48 | for (int i = 0; i < veggies.length; i++) { 49 | result.append(veggies[i]); 50 | if (i < veggies.length-1) { 51 | result.append(", "); 52 | } 53 | } 54 | result.append("\n"); 55 | } 56 | if (clam != null) { 57 | result.append(clam); 58 | result.append("\n"); 59 | } 60 | if (pepperoni != null) { 61 | result.append(pepperoni); 62 | result.append("\n"); 63 | } 64 | return result.toString(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/PizzaIngredientFactory.java: -------------------------------------------------------------------------------- 1 | public interface PizzaIngredientFactory { 2 | 3 | public Dough createDough(); 4 | public Sauce createSauce(); 5 | public Cheese createCheese(); 6 | public Veggies[] createVeggies(); 7 | public Pepperoni createPepperoni(); 8 | public Clams createClam(); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/PizzaStore.java: -------------------------------------------------------------------------------- 1 | public abstract class PizzaStore { 2 | 3 | protected abstract Pizza createPizza(String item); 4 | 5 | public Pizza orderPizza(String type) { 6 | Pizza pizza = createPizza(type); 7 | System.out.println("--- Making a " + pizza.getName() + " ---"); 8 | pizza.prepare(); 9 | pizza.bake(); 10 | pizza.cut(); 11 | pizza.box(); 12 | return pizza; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/PizzaTestDrive.java: -------------------------------------------------------------------------------- 1 | public class PizzaTestDrive { 2 | 3 | public static void main(String[] args) { 4 | PizzaStore nyStore = new NYPizzaStore(); 5 | PizzaStore chicagoStore = new ChicagoPizzaStore(); 6 | 7 | Pizza pizza = nyStore.orderPizza("cheese"); 8 | System.out.println("Ethan ordered a " + pizza + "\n"); 9 | 10 | pizza = chicagoStore.orderPizza("cheese"); 11 | System.out.println("Joel ordered a " + pizza + "\n"); 12 | 13 | pizza = nyStore.orderPizza("clam"); 14 | System.out.println("Ethan ordered a " + pizza + "\n"); 15 | 16 | pizza = chicagoStore.orderPizza("clam"); 17 | System.out.println("Joel ordered a " + pizza + "\n"); 18 | 19 | pizza = nyStore.orderPizza("pepperoni"); 20 | System.out.println("Ethan ordered a " + pizza + "\n"); 21 | 22 | pizza = chicagoStore.orderPizza("pepperoni"); 23 | System.out.println("Joel ordered a " + pizza + "\n"); 24 | 25 | pizza = nyStore.orderPizza("veggie"); 26 | System.out.println("Ethan ordered a " + pizza + "\n"); 27 | 28 | pizza = chicagoStore.orderPizza("veggie"); 29 | System.out.println("Joel ordered a " + pizza + "\n"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/PlumTomatoSauce.java: -------------------------------------------------------------------------------- 1 | public class PlumTomatoSauce implements Sauce { 2 | 3 | public String toString() { 4 | return "Tomato sauce with plum tomatoes"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/RedPepper.java: -------------------------------------------------------------------------------- 1 | public class RedPepper implements Veggies { 2 | 3 | public String toString() { 4 | return "Red Pepper"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ReggianoCheese.java: -------------------------------------------------------------------------------- 1 | public class ReggianoCheese implements Cheese { 2 | 3 | public String toString() { 4 | return "Reggiano Cheese"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Sauce.java: -------------------------------------------------------------------------------- 1 | public interface Sauce { 2 | public String toString(); 3 | } 4 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/SlicedPepperoni.java: -------------------------------------------------------------------------------- 1 | public class SlicedPepperoni implements Pepperoni { 2 | 3 | public String toString() { 4 | return "Sliced Pepperoni"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Spinach.java: -------------------------------------------------------------------------------- 1 | public class Spinach implements Veggies { 2 | 3 | public String toString() { 4 | return "Spinach"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ThickCrustDough.java: -------------------------------------------------------------------------------- 1 | public class ThickCrustDough implements Dough { 2 | 3 | public String toString() { 4 | return "ThickCrust style extra thick crust dough"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/ThinCrustDough.java: -------------------------------------------------------------------------------- 1 | public class ThinCrustDough implements Dough { 2 | 3 | public String toString() { 4 | return "Thin Crust Dough"; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | public class VeggiePizza extends Pizza { 2 | PizzaIngredientFactory ingredientFactory; 3 | 4 | public VeggiePizza(PizzaIngredientFactory ingredientFactory) { 5 | this.ingredientFactory = ingredientFactory; 6 | } 7 | 8 | void prepare() { 9 | System.out.println("Preparing " + name); 10 | dough = ingredientFactory.createDough(); 11 | sauce = ingredientFactory.createSauce(); 12 | cheese = ingredientFactory.createCheese(); 13 | veggies = ingredientFactory.createVeggies(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/factory/pizzaaf/Veggies.java: -------------------------------------------------------------------------------- 1 | public interface Veggies { 2 | public String toString(); 3 | } 4 | -------------------------------------------------------------------------------- /java/factory/pizzafm/ChicagoPizzaStore.java: -------------------------------------------------------------------------------- 1 | public class ChicagoPizzaStore extends PizzaStore { 2 | 3 | Pizza createPizza(String item) { 4 | if (item.equals("cheese")) { 5 | return new ChicagoStyleCheesePizza(); 6 | } else if (item.equals("veggie")) { 7 | return new ChicagoStyleVeggiePizza(); 8 | } else if (item.equals("clam")) { 9 | return new ChicagoStyleClamPizza(); 10 | } else if (item.equals("pepperoni")) { 11 | return new ChicagoStylePepperoniPizza(); 12 | } else { 13 | return null; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/factory/pizzafm/ChicagoStyleCheesePizza.java: -------------------------------------------------------------------------------- 1 | public class ChicagoStyleCheesePizza extends Pizza { 2 | 3 | public ChicagoStyleCheesePizza() { 4 | name = "Chicago Style Deep Dish Cheese Pizza"; 5 | dough = "Extra Thick Crust Dough"; 6 | sauce = "Plum Tomato Sauce"; 7 | 8 | toppings.add("Shredded Mozzarella Cheese"); 9 | } 10 | 11 | void cut() { 12 | System.out.println("Cutting the pizza into square slices"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/factory/pizzafm/ChicagoStyleClamPizza.java: -------------------------------------------------------------------------------- 1 | public class ChicagoStyleClamPizza extends Pizza { 2 | 3 | public ChicagoStyleClamPizza() { 4 | name = "Chicago Style Clam Pizza"; 5 | dough = "Extra Thick Crust Dough"; 6 | sauce = "Plum Tomato Sauce"; 7 | 8 | toppings.add("Shredded Mozzarella Cheese"); 9 | toppings.add("Frozen Clams from Chesapeake Bay"); 10 | } 11 | 12 | void cut() { 13 | System.out.println("Cutting the pizza into square slices"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/factory/pizzafm/ChicagoStylePepperoniPizza.java: -------------------------------------------------------------------------------- 1 | public class ChicagoStylePepperoniPizza extends Pizza { 2 | 3 | public ChicagoStylePepperoniPizza() { 4 | name = "Chicago Style Pepperoni Pizza"; 5 | dough = "Extra Thick Crust Dough"; 6 | sauce = "Plum Tomato Sauce"; 7 | 8 | toppings.add("Shredded Mozzarella Cheese"); 9 | toppings.add("Black Olives"); 10 | toppings.add("Spinach"); 11 | toppings.add("Eggplant"); 12 | toppings.add("Sliced Pepperoni"); 13 | } 14 | 15 | void cut() { 16 | System.out.println("Cutting the pizza into square slices"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/factory/pizzafm/ChicagoStyleVeggiePizza.java: -------------------------------------------------------------------------------- 1 | public class ChicagoStyleVeggiePizza extends Pizza { 2 | 3 | public ChicagoStyleVeggiePizza() { 4 | name = "Chicago Deep Dish Veggie Pizza"; 5 | dough = "Extra Thick Crust Dough"; 6 | sauce = "Plum Tomato Sauce"; 7 | 8 | toppings.add("Shredded Mozzarella Cheese"); 9 | toppings.add("Black Olives"); 10 | toppings.add("Spinach"); 11 | toppings.add("Eggplant"); 12 | } 13 | 14 | void cut() { 15 | System.out.println("Cutting the pizza into square slices"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/factory/pizzafm/NYPizzaStore.java: -------------------------------------------------------------------------------- 1 | public class NYPizzaStore extends PizzaStore { 2 | 3 | Pizza createPizza(String item) { 4 | if (item.equals("cheese")) { 5 | return new NYStyleCheesePizza(); 6 | } else if (item.equals("veggie")) { 7 | return new NYStyleVeggiePizza(); 8 | } else if (item.equals("clam")) { 9 | return new NYStyleClamPizza(); 10 | } else if (item.equals("pepperoni")) { 11 | return new NYStylePepperoniPizza(); 12 | } else return null; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/factory/pizzafm/NYStyleCheesePizza.java: -------------------------------------------------------------------------------- 1 | public class NYStyleCheesePizza extends Pizza { 2 | 3 | public NYStyleCheesePizza() { 4 | name = "NY Style Sauce and Cheese Pizza"; 5 | dough = "Thin Crust Dough"; 6 | sauce = "Marinara Sauce"; 7 | 8 | toppings.add("Grated Reggiano Cheese"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/factory/pizzafm/NYStyleClamPizza.java: -------------------------------------------------------------------------------- 1 | public class NYStyleClamPizza extends Pizza { 2 | 3 | public NYStyleClamPizza() { 4 | name = "NY Style Clam Pizza"; 5 | dough = "Thin Crust Dough"; 6 | sauce = "Marinara Sauce"; 7 | 8 | toppings.add("Grated Reggiano Cheese"); 9 | toppings.add("Fresh Clams from Long Island Sound"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/factory/pizzafm/NYStylePepperoniPizza.java: -------------------------------------------------------------------------------- 1 | public class NYStylePepperoniPizza extends Pizza { 2 | 3 | public NYStylePepperoniPizza() { 4 | name = "NY Style Pepperoni Pizza"; 5 | dough = "Thin Crust Dough"; 6 | sauce = "Marinara Sauce"; 7 | 8 | toppings.add("Grated Reggiano Cheese"); 9 | toppings.add("Sliced Pepperoni"); 10 | toppings.add("Garlic"); 11 | toppings.add("Onion"); 12 | toppings.add("Mushrooms"); 13 | toppings.add("Red Pepper"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/factory/pizzafm/NYStyleVeggiePizza.java: -------------------------------------------------------------------------------- 1 | public class NYStyleVeggiePizza extends Pizza { 2 | 3 | public NYStyleVeggiePizza() { 4 | name = "NY Style Veggie Pizza"; 5 | dough = "Thin Crust Dough"; 6 | sauce = "Marinara Sauce"; 7 | 8 | toppings.add("Grated Reggiano Cheese"); 9 | toppings.add("Garlic"); 10 | toppings.add("Onion"); 11 | toppings.add("Mushrooms"); 12 | toppings.add("Red Pepper"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/factory/pizzafm/Pizza.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public abstract class Pizza { 4 | String name; 5 | String dough; 6 | String sauce; 7 | ArrayList toppings = new ArrayList(); 8 | 9 | void prepare() { 10 | System.out.println("Preparing " + name); 11 | System.out.println("Tossing dough..."); 12 | System.out.println("Adding sauce..."); 13 | System.out.println("Adding toppings: "); 14 | for (int i = 0; i < toppings.size(); i++) { 15 | System.out.println(" " + toppings.get(i)); 16 | } 17 | } 18 | 19 | void bake() { 20 | System.out.println("Bake for 25 minutes at 350"); 21 | } 22 | 23 | void cut() { 24 | System.out.println("Cutting the pizza into diagonal slices"); 25 | } 26 | 27 | void box() { 28 | System.out.println("Place pizza in official PizzaStore box"); 29 | } 30 | 31 | public String getName() { 32 | return name; 33 | } 34 | 35 | public String toString() { 36 | StringBuffer display = new StringBuffer(); 37 | display.append("---- " + name + " ----\n"); 38 | display.append(dough + "\n"); 39 | display.append(sauce + "\n"); 40 | for (int i = 0; i < toppings.size(); i++) { 41 | display.append((String )toppings.get(i) + "\n"); 42 | } 43 | return display.toString(); 44 | } 45 | } 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /java/factory/pizzafm/PizzaStore.java: -------------------------------------------------------------------------------- 1 | public abstract class PizzaStore { 2 | 3 | abstract Pizza createPizza(String item); 4 | 5 | public Pizza orderPizza(String type) { 6 | Pizza pizza = createPizza(type); 7 | System.out.println("--- Making a " + pizza.getName() + " ---"); 8 | pizza.prepare(); 9 | pizza.bake(); 10 | pizza.cut(); 11 | pizza.box(); 12 | return pizza; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/factory/pizzafm/PizzaTestDrive.java: -------------------------------------------------------------------------------- 1 | public class PizzaTestDrive { 2 | 3 | public static void main(String[] args) { 4 | PizzaStore nyStore = new NYPizzaStore(); 5 | PizzaStore chicagoStore = new ChicagoPizzaStore(); 6 | 7 | Pizza pizza = nyStore.orderPizza("cheese"); 8 | System.out.println("Ethan ordered a " + pizza.getName() + "\n"); 9 | 10 | pizza = chicagoStore.orderPizza("cheese"); 11 | System.out.println("Joel ordered a " + pizza.getName() + "\n"); 12 | 13 | pizza = nyStore.orderPizza("clam"); 14 | System.out.println("Ethan ordered a " + pizza.getName() + "\n"); 15 | 16 | pizza = chicagoStore.orderPizza("clam"); 17 | System.out.println("Joel ordered a " + pizza.getName() + "\n"); 18 | 19 | pizza = nyStore.orderPizza("pepperoni"); 20 | System.out.println("Ethan ordered a " + pizza.getName() + "\n"); 21 | 22 | pizza = chicagoStore.orderPizza("pepperoni"); 23 | System.out.println("Joel ordered a " + pizza.getName() + "\n"); 24 | 25 | pizza = nyStore.orderPizza("veggie"); 26 | System.out.println("Ethan ordered a " + pizza.getName() + "\n"); 27 | 28 | pizza = chicagoStore.orderPizza("veggie"); 29 | System.out.println("Joel ordered a " + pizza.getName() + "\n"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/iterator/dinermerger/DinerMenu.java: -------------------------------------------------------------------------------- 1 | public class DinerMenu { 2 | static final int MAX_ITEMS = 6; 3 | int numberOfItems = 0; 4 | MenuItem[] menuItems; 5 | 6 | public DinerMenu() { 7 | menuItems = new MenuItem[MAX_ITEMS]; 8 | 9 | addItem("Vegetarian BLT", 10 | "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99); 11 | addItem("BLT", 12 | "Bacon with lettuce & tomato on whole wheat", false, 2.99); 13 | addItem("Soup of the day", 14 | "Soup of the day, with a side of potato salad", false, 3.29); 15 | addItem("Hotdog", 16 | "A hot dog, with saurkraut, relish, onions, topped with cheese", 17 | false, 3.05); 18 | addItem("Steamed Veggies and Brown Rice", 19 | "Steamed vegetables over brown rice", true, 3.99); 20 | addItem("Pasta", 21 | "Spaghetti with Marinara Sauce, and a slice of sourdough bread", 22 | true, 3.89); 23 | } 24 | 25 | public void addItem(String name, String description, boolean vegetarian, double price) { 26 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 27 | 28 | if (numberOfItems >= MAX_ITEMS) { 29 | System.err.println("Sorry, menu is full! Can't add item to menu"); 30 | } 31 | else { 32 | menuItems[numberOfItems] = menuItem; 33 | numberOfItems = numberOfItems + 1; 34 | } 35 | } 36 | 37 | // This method is not going to be used after we have the createIterator() method 38 | public MenuItem[] getMenuItems() { 39 | return menuItems; 40 | } 41 | 42 | public Iterator createIterator() { 43 | return new DinerMenuIterator(menuItems); 44 | } 45 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/DinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | public class DinerMenuIterator implements Iterator { 2 | MenuItem[] items; 3 | int position = 0; 4 | 5 | public DinerMenuIterator(MenuItem[] items) { 6 | this.items = items; 7 | } 8 | 9 | public Object next() { 10 | MenuItem menuItem = items[position]; 11 | position = position + 1; 12 | return menuItem; 13 | } 14 | 15 | public boolean hasNext() { 16 | if (position >= items.length || items[position] == null) { 17 | return false; 18 | } 19 | else { 20 | return true; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/Iterator.java: -------------------------------------------------------------------------------- 1 | public interface Iterator { 2 | boolean hasNext(); 3 | Object next(); 4 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/MenuItem.java: -------------------------------------------------------------------------------- 1 | public class MenuItem { 2 | String name; 3 | String description; 4 | boolean vegetarian; 5 | double price; 6 | 7 | public MenuItem(String name, 8 | String description, 9 | boolean vegetarian, 10 | double price) { 11 | this.name = name; 12 | this.description = description; 13 | this.vegetarian = vegetarian; 14 | this.price = price; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public String getDescription() { 22 | return description; 23 | } 24 | 25 | public boolean isVegetarian() { 26 | return vegetarian; 27 | } 28 | 29 | public double getPrice() { 30 | return price; 31 | } 32 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/MenuTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class MenuTestDrive { 4 | 5 | public static void main(String[] args) { 6 | PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu(); 7 | DinerMenu dinerMenu = new DinerMenu(); 8 | 9 | Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu); 10 | waitress.printMenu(); 11 | } 12 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/PancakeHouseMenu.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class PancakeHouseMenu { 4 | ArrayList menuItems; 5 | 6 | public PancakeHouseMenu() { 7 | menuItems = new ArrayList(); 8 | 9 | addItem("K&B's Pancake Breakfast", 10 | "Pancakes with scrambled eggs, and toast", 11 | true, 12 | 2.99); 13 | 14 | addItem("Regular Pancake Breakfast", 15 | "Pancakes with fried eggs, sausage", 16 | false, 17 | 2.99); 18 | 19 | addItem("Blueberry Pancakes", 20 | "Pancakes made with fresh blueberries", 21 | true, 22 | 3.49); 23 | 24 | addItem("Waffles", 25 | "Waffles, with your choice of blueberries or strawberries", 26 | true, 27 | 3.59); 28 | } 29 | 30 | public void addItem(String name, String description, boolean vegetarian, double price) { 31 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 32 | menuItems.add(menuItem); 33 | } 34 | 35 | public ArrayList getMenuItems() { 36 | return menuItems; 37 | } 38 | 39 | public Iterator createIterator() { 40 | return new PancakeHouseMenuIterator(menuItems); 41 | } 42 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/PancakeHouseMenuIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class PancakeHouseMenuIterator implements Iterator { 4 | ArrayList items; 5 | int position = 0; 6 | 7 | public PancakeHouseMenuIterator(ArrayList items) { 8 | this.items = items; 9 | } 10 | 11 | public Object next() { 12 | Object object = items.get(position); 13 | position = position + 1; 14 | return object; 15 | } 16 | 17 | public boolean hasNext() { 18 | if (position >= items.size()) { 19 | return false; 20 | } 21 | else { 22 | return true; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /java/iterator/dinermerger/Waitress.java: -------------------------------------------------------------------------------- 1 | public class Waitress { 2 | PancakeHouseMenu pancakeHouseMenu; 3 | DinerMenu dinerMenu; 4 | 5 | public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) { 6 | this.pancakeHouseMenu = pancakeHouseMenu; 7 | this.dinerMenu = dinerMenu; 8 | } 9 | 10 | public void printMenu() { 11 | Iterator pancakeIterator = pancakeHouseMenu.createIterator(); 12 | Iterator dinerIterator = dinerMenu.createIterator(); 13 | System.out.println("MENU\n----\nBREAKFAST"); 14 | printMenu(pancakeIterator); 15 | System.out.println("\nLUNCH"); 16 | printMenu(dinerIterator); 17 | } 18 | 19 | private void printMenu(Iterator iterator) { 20 | while (iterator.hasNext()) { 21 | MenuItem menuItem = (MenuItem)iterator.next(); 22 | System.out.println(menuItem.getName() + ", "); 23 | System.out.println(menuItem.getPrice() + " -- "); 24 | System.out.println(menuItem.getDescription()); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/CafeMenu.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.Iterator; 3 | 4 | public class CafeMenu implements Menu { 5 | Hashtable menuItems = new Hashtable(); 6 | 7 | public CafeMenu() { 8 | addItem("Veggie Burger and Air Fries", 9 | "Veggie burger on a whole wheat bun, lettuce, tomato, and fries", 10 | true, 3.99); 11 | addItem("Soup of the day", 12 | "A cup of the soup of the day, with a side salad", 13 | false, 3.69); 14 | addItem("Burrito", 15 | "A large burrito, with whole pinto beans, salsa, guacamole", 16 | true, 4.29); 17 | } 18 | 19 | public void addItem(String name, String description, 20 | boolean vegetarian, double price) 21 | { 22 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 23 | menuItems.put(menuItem.getName(), menuItem); 24 | } 25 | 26 | public Iterator createIterator() { 27 | return menuItems.values().iterator(); 28 | } 29 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/DinerMenu.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class DinerMenu implements Menu { 4 | static final int MAX_ITEMS = 6; 5 | int numberOfItems = 0; 6 | MenuItem[] menuItems; 7 | 8 | public DinerMenu() { 9 | menuItems = new MenuItem[MAX_ITEMS]; 10 | 11 | addItem("Vegetarian BLT", 12 | "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99); 13 | addItem("BLT", 14 | "Bacon with lettuce & tomato on whole wheat", false, 2.99); 15 | addItem("Soup of the day", 16 | "Soup of the day, with a side of potato salad", false, 3.29); 17 | addItem("Hotdog", 18 | "A hot dog, with saurkraut, relish, onions, topped with cheese", 19 | false, 3.05); 20 | addItem("Steamed Veggies and Brown Rice", 21 | "Steamed vegetables over brown rice", true, 3.99); 22 | addItem("Pasta", 23 | "Spaghetti with Marinara Sauce, and a slice of sourdough bread", 24 | true, 3.89); 25 | } 26 | 27 | public void addItem(String name, String description, boolean vegetarian, double price) { 28 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 29 | 30 | if (numberOfItems >= MAX_ITEMS) { 31 | System.err.println("Sorry, menu is full! Can't add item to menu"); 32 | } 33 | else { 34 | menuItems[numberOfItems] = menuItem; 35 | numberOfItems = numberOfItems + 1; 36 | } 37 | } 38 | 39 | // This method is not going to be used after we have the createIterator() method 40 | public MenuItem[] getMenuItems() { 41 | return menuItems; 42 | } 43 | 44 | public Iterator createIterator() { 45 | return new DinerMenuIterator(menuItems); 46 | } 47 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/DinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class DinerMenuIterator implements Iterator { 4 | MenuItem[] items; 5 | int position = 0; 6 | 7 | public DinerMenuIterator(MenuItem[] items) { 8 | this.items = items; 9 | } 10 | 11 | public Object next() { 12 | MenuItem menuItem = items[position]; 13 | position = position + 1; 14 | return menuItem; 15 | } 16 | 17 | public boolean hasNext() { 18 | if (position >= items.length || items[position] == null) { 19 | return false; 20 | } 21 | else { 22 | return true; 23 | } 24 | } 25 | 26 | public void remove() { 27 | if (position <= 0) { 28 | throw new IllegalStateException("You can't remove an item until you've one at least one next()"); 29 | } 30 | if (items[position - 1] != null) { 31 | for (int i = position - 1; i < (items.length - 1); i++) { 32 | items[i] = items[i + 1]; 33 | } 34 | items[items.length -1] = null; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/Iterator.java: -------------------------------------------------------------------------------- 1 | public interface Iterator { 2 | boolean hasNext(); 3 | Object next(); 4 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/Menu.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public interface Menu { 4 | public Iterator createIterator(); 5 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/MenuItem.java: -------------------------------------------------------------------------------- 1 | public class MenuItem { 2 | String name; 3 | String description; 4 | boolean vegetarian; 5 | double price; 6 | 7 | public MenuItem(String name, 8 | String description, 9 | boolean vegetarian, 10 | double price) { 11 | this.name = name; 12 | this.description = description; 13 | this.vegetarian = vegetarian; 14 | this.price = price; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public String getDescription() { 22 | return description; 23 | } 24 | 25 | public boolean isVegetarian() { 26 | return vegetarian; 27 | } 28 | 29 | public double getPrice() { 30 | return price; 31 | } 32 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/MenuTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class MenuTestDrive { 4 | 5 | public static void main(String[] args) { 6 | PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu(); 7 | DinerMenu dinerMenu = new DinerMenu(); 8 | CafeMenu cafeMenu = new CafeMenu(); 9 | 10 | Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu, cafeMenu); 11 | waitress.printMenu(); 12 | } 13 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/PancakeHouseMenu.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | 4 | public class PancakeHouseMenu implements Menu { 5 | ArrayList menuItems; 6 | 7 | public PancakeHouseMenu() { 8 | menuItems = new ArrayList(); 9 | 10 | addItem("K&B's Pancake Breakfast", 11 | "Pancakes with scrambled eggs, and toast", 12 | true, 13 | 2.99); 14 | 15 | addItem("Regular Pancake Breakfast", 16 | "Pancakes with fried eggs, sausage", 17 | false, 18 | 2.99); 19 | 20 | addItem("Blueberry Pancakes", 21 | "Pancakes made with fresh blueberries", 22 | true, 23 | 3.49); 24 | 25 | addItem("Waffles", 26 | "Waffles, with your choice of blueberries or strawberries", 27 | true, 28 | 3.59); 29 | } 30 | 31 | public void addItem(String name, String description, boolean vegetarian, double price) { 32 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 33 | menuItems.add(menuItem); 34 | } 35 | 36 | public ArrayList getMenuItems() { 37 | return menuItems; 38 | } 39 | 40 | public Iterator createIterator() { 41 | return menuItems.iterator(); 42 | } 43 | } -------------------------------------------------------------------------------- /java/iterator/dinermergercafe/Waitress.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class Waitress { 4 | Menu pancakeHouseMenu; 5 | Menu dinerMenu; 6 | Menu cafeMenu; 7 | 8 | public Waitress(Menu pancakeHouseMenu, Menu dinerMenu, Menu cafeMenu) { 9 | this.pancakeHouseMenu = pancakeHouseMenu; 10 | this.dinerMenu = dinerMenu; 11 | this.cafeMenu = cafeMenu; 12 | } 13 | 14 | public void printMenu() { 15 | Iterator pancakeIterator = pancakeHouseMenu.createIterator(); 16 | Iterator dinerIterator = dinerMenu.createIterator(); 17 | Iterator cafeIterator = cafeMenu.createIterator(); 18 | System.out.println("MENU\n----\nBREAKFAST"); 19 | printMenu(pancakeIterator); 20 | System.out.println("\nLUNCH"); 21 | printMenu(dinerIterator); 22 | System.out.println("\nDINNER"); 23 | printMenu(cafeIterator); 24 | } 25 | 26 | private void printMenu(Iterator iterator) { 27 | while (iterator.hasNext()) { 28 | MenuItem menuItem = (MenuItem)iterator.next(); 29 | System.out.println(menuItem.getName() + ", "); 30 | System.out.println(menuItem.getPrice() + " -- "); 31 | System.out.println(menuItem.getDescription()); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/DinerMenu.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class DinerMenu implements Menu { 4 | static final int MAX_ITEMS = 6; 5 | int numberOfItems = 0; 6 | MenuItem[] menuItems; 7 | 8 | public DinerMenu() { 9 | menuItems = new MenuItem[MAX_ITEMS]; 10 | 11 | addItem("Vegetarian BLT", 12 | "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99); 13 | addItem("BLT", 14 | "Bacon with lettuce & tomato on whole wheat", false, 2.99); 15 | addItem("Soup of the day", 16 | "Soup of the day, with a side of potato salad", false, 3.29); 17 | addItem("Hotdog", 18 | "A hot dog, with saurkraut, relish, onions, topped with cheese", 19 | false, 3.05); 20 | addItem("Steamed Veggies and Brown Rice", 21 | "Steamed vegetables over brown rice", true, 3.99); 22 | addItem("Pasta", 23 | "Spaghetti with Marinara Sauce, and a slice of sourdough bread", 24 | true, 3.89); 25 | } 26 | 27 | public void addItem(String name, String description, boolean vegetarian, double price) { 28 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 29 | 30 | if (numberOfItems >= MAX_ITEMS) { 31 | System.err.println("Sorry, menu is full! Can't add item to menu"); 32 | } 33 | else { 34 | menuItems[numberOfItems] = menuItem; 35 | numberOfItems = numberOfItems + 1; 36 | } 37 | } 38 | 39 | // This method is not going to be used after we have the createIterator() method 40 | public MenuItem[] getMenuItems() { 41 | return menuItems; 42 | } 43 | 44 | public Iterator createIterator() { 45 | return new DinerMenuIterator(menuItems); 46 | } 47 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/DinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class DinerMenuIterator implements Iterator { 4 | MenuItem[] items; 5 | int position = 0; 6 | 7 | public DinerMenuIterator(MenuItem[] items) { 8 | this.items = items; 9 | } 10 | 11 | public Object next() { 12 | MenuItem menuItem = items[position]; 13 | position = position + 1; 14 | return menuItem; 15 | } 16 | 17 | public boolean hasNext() { 18 | if (position >= items.length || items[position] == null) { 19 | return false; 20 | } 21 | else { 22 | return true; 23 | } 24 | } 25 | 26 | public void remove() { 27 | if (position <= 0) { 28 | throw new IllegalStateException("You can't remove an item until you've one at least one next()"); 29 | } 30 | if (items[position - 1] != null) { 31 | for (int i = position - 1; i < (items.length - 1); i++) { 32 | items[i] = items[i + 1]; 33 | } 34 | items[items.length -1] = null; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/Iterator.java: -------------------------------------------------------------------------------- 1 | public interface Iterator { 2 | boolean hasNext(); 3 | Object next(); 4 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/Menu.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public interface Menu { 4 | public Iterator createIterator(); 5 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/MenuItem.java: -------------------------------------------------------------------------------- 1 | public class MenuItem { 2 | String name; 3 | String description; 4 | boolean vegetarian; 5 | double price; 6 | 7 | public MenuItem(String name, 8 | String description, 9 | boolean vegetarian, 10 | double price) { 11 | this.name = name; 12 | this.description = description; 13 | this.vegetarian = vegetarian; 14 | this.price = price; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public String getDescription() { 22 | return description; 23 | } 24 | 25 | public boolean isVegetarian() { 26 | return vegetarian; 27 | } 28 | 29 | public double getPrice() { 30 | return price; 31 | } 32 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/MenuTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class MenuTestDrive { 4 | 5 | public static void main(String[] args) { 6 | PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu(); 7 | DinerMenu dinerMenu = new DinerMenu(); 8 | 9 | Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu); 10 | waitress.printMenu(); 11 | } 12 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/PancakeHouseMenu.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | 4 | public class PancakeHouseMenu implements Menu { 5 | ArrayList menuItems; 6 | 7 | public PancakeHouseMenu() { 8 | menuItems = new ArrayList(); 9 | 10 | addItem("K&B's Pancake Breakfast", 11 | "Pancakes with scrambled eggs, and toast", 12 | true, 13 | 2.99); 14 | 15 | addItem("Regular Pancake Breakfast", 16 | "Pancakes with fried eggs, sausage", 17 | false, 18 | 2.99); 19 | 20 | addItem("Blueberry Pancakes", 21 | "Pancakes made with fresh blueberries", 22 | true, 23 | 3.49); 24 | 25 | addItem("Waffles", 26 | "Waffles, with your choice of blueberries or strawberries", 27 | true, 28 | 3.59); 29 | } 30 | 31 | public void addItem(String name, String description, boolean vegetarian, double price) { 32 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 33 | menuItems.add(menuItem); 34 | } 35 | 36 | public ArrayList getMenuItems() { 37 | return menuItems; 38 | } 39 | 40 | public Iterator createIterator() { 41 | return menuItems.iterator(); 42 | } 43 | } -------------------------------------------------------------------------------- /java/iterator/dinermergeri/Waitress.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class Waitress { 4 | Menu pancakeHouseMenu; 5 | Menu dinerMenu; 6 | 7 | public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) { 8 | this.pancakeHouseMenu = pancakeHouseMenu; 9 | this.dinerMenu = dinerMenu; 10 | } 11 | 12 | public void printMenu() { 13 | Iterator pancakeIterator = pancakeHouseMenu.createIterator(); 14 | Iterator dinerIterator = dinerMenu.createIterator(); 15 | System.out.println("MENU\n----\nBREAKFAST"); 16 | printMenu(pancakeIterator); 17 | System.out.println("\nLUNCH"); 18 | printMenu(dinerIterator); 19 | } 20 | 21 | private void printMenu(Iterator iterator) { 22 | while (iterator.hasNext()) { 23 | MenuItem menuItem = (MenuItem)iterator.next(); 24 | System.out.println(menuItem.getName() + ", "); 25 | System.out.println(menuItem.getPrice() + " -- "); 26 | System.out.println(menuItem.getDescription()); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /java/observer/swing/SwingObserverExample.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | import javax.swing.*; 4 | import javax.swing.event.*; 5 | 6 | public class SwingObserverExample { 7 | JFrame frame; 8 | 9 | public static void main(String[] args) { 10 | SwingObserverExample example = new SwingObserverExample(); 11 | example.go(); 12 | } 13 | 14 | public void go() { 15 | frame = new JFrame(); 16 | JButton button = new JButton("Should I do it?"); 17 | button.addActionListener(new AngelListener()); 18 | button.addActionListener(new DevilListener()); 19 | frame.getContentPane().add(BorderLayout.CENTER, button); 20 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 | frame.getContentPane().add(BorderLayout.CENTER, button); 22 | frame.setSize(300,300); 23 | frame.setVisible(true); 24 | } 25 | 26 | class AngelListener implements ActionListener { 27 | public void actionPerformed(ActionEvent event) { 28 | System.out.println("Don't do it, you might regret it!"); 29 | } 30 | } 31 | 32 | class DevilListener implements ActionListener { 33 | public void actionPerformed(ActionEvent event) { 34 | System.out.println("Come on, do it!"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/observer/weather/CurrentConditionsDisplay.java: -------------------------------------------------------------------------------- 1 | public class CurrentConditionsDisplay implements Observer, DisplayElement { 2 | private float temperature; 3 | private float humidity; 4 | private Subject weatherData; 5 | 6 | public CurrentConditionsDisplay(Subject weatherData) { 7 | this.weatherData = weatherData; 8 | weatherData.registerObserver(this); 9 | } 10 | 11 | public void update(float temperature, float humidity, float pressure) { 12 | this.temperature = temperature; 13 | this.humidity = humidity; 14 | display(); // Not very good to call display() inside of update(). See MVC 15 | } 16 | 17 | public void display() { 18 | System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); 19 | } 20 | } -------------------------------------------------------------------------------- /java/observer/weather/DisplayElement.java: -------------------------------------------------------------------------------- 1 | public interface DisplayElement { 2 | public void display(); 3 | } -------------------------------------------------------------------------------- /java/observer/weather/ForecastDisplay.java: -------------------------------------------------------------------------------- 1 | public class ForecastDisplay implements Observer, DisplayElement { 2 | private float currentPressure = 29.92f; 3 | private float lastPressure; 4 | private Subject weatherData; 5 | 6 | public ForecastDisplay(Subject weatherData) { 7 | this.weatherData = weatherData; 8 | weatherData.registerObserver(this); 9 | } 10 | 11 | public void update(float temperature, float humidity, float pressure) { 12 | lastPressure = currentPressure; 13 | currentPressure = pressure; 14 | 15 | display(); 16 | } 17 | 18 | public void display() { 19 | System.out.print("Forecast: "); 20 | if (currentPressure > lastPressure) { 21 | System.out.println("Improving weather on the way!"); 22 | } else if (currentPressure == lastPressure) { 23 | System.out.println("More of the same"); 24 | } else if (currentPressure < lastPressure) { 25 | System.out.println("Watch out for cooler, rainy weather"); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /java/observer/weather/HeatIndexDisplay.java: -------------------------------------------------------------------------------- 1 | public class HeatIndexDisplay implements Observer, DisplayElement { 2 | float heatIndex = 0.0f; 3 | private Subject weatherData; 4 | 5 | public HeatIndexDisplay(Subject weatherData) { 6 | this.weatherData = weatherData; 7 | weatherData.registerObserver(this); 8 | } 9 | 10 | public void update(float temperature, float humidity, float pressure) { 11 | heatIndex = computeHeatIndex(temperature, humidity); 12 | display(); 13 | } 14 | 15 | public void display() { 16 | System.out.println("Heat index is " + heatIndex); 17 | } 18 | 19 | private float computeHeatIndex(float t, float rh) { 20 | float index = (float)((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh) 21 | + (0.00941695 * (t * t)) + (0.00728898 * (rh * rh)) 22 | + (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) + 23 | (0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 * 24 | (rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) + 25 | (0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) + 26 | 0.000000000843296 * (t * t * rh * rh * rh)) - 27 | (0.0000000000481975 * (t * t * t * rh * rh * rh))); 28 | return index; 29 | } 30 | } -------------------------------------------------------------------------------- /java/observer/weather/Observer.java: -------------------------------------------------------------------------------- 1 | public interface Observer { 2 | public void update(float temp, float humidity, float pressure); 3 | } -------------------------------------------------------------------------------- /java/observer/weather/StatisticsDisplay.java: -------------------------------------------------------------------------------- 1 | public class StatisticsDisplay implements Observer, DisplayElement { 2 | private float maxTemp = 0.0f; 3 | private float minTemp = 200; 4 | private float tempSum = 0.0f; 5 | private int numReadings; 6 | private Subject weatherData; 7 | 8 | public StatisticsDisplay(Subject weatherData) { 9 | this.weatherData = weatherData; 10 | weatherData.registerObserver(this); 11 | } 12 | 13 | public void update(float temperature, float humidity, float pressure) { 14 | tempSum += temperature; 15 | numReadings++; 16 | 17 | if (temperature > maxTemp) { 18 | maxTemp = temperature; 19 | } 20 | 21 | if (temperature < minTemp) { 22 | minTemp = temperature; 23 | } 24 | 25 | display(); 26 | } 27 | 28 | public void display() { 29 | System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings) + "/" + maxTemp + "/" + minTemp); 30 | } 31 | } -------------------------------------------------------------------------------- /java/observer/weather/Subject.java: -------------------------------------------------------------------------------- 1 | public interface Subject { 2 | public void registerObserver(Observer o); 3 | public void removeObserver(Observer o); 4 | public void notifyObservers(); 5 | } -------------------------------------------------------------------------------- /java/observer/weather/WeatherData.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class WeatherData implements Subject { 4 | private ArrayList observers; 5 | private float temperature; 6 | private float humidity; 7 | private float pressure; 8 | 9 | public WeatherData() { 10 | observers = new ArrayList(); 11 | } 12 | 13 | public void registerObserver(Observer o) { 14 | observers.add(o); 15 | } 16 | 17 | public void removeObserver(Observer o) { 18 | int i = observers.indexOf(o); 19 | if (i >= 0) { 20 | observers.remove(i); 21 | } 22 | } 23 | 24 | public void notifyObservers() { 25 | for (int i = 0; i < observers.size(); i++) { 26 | Observer observer = (Observer)observers.get(i); 27 | observer.update(temperature, humidity, pressure); 28 | } 29 | } 30 | 31 | public void measurementsChanged() { 32 | notifyObservers(); 33 | } 34 | 35 | public void setMeasurements(float temperature, float humidity, float pressure) { 36 | this.temperature = temperature; 37 | this.humidity = humidity; 38 | this.pressure = pressure; 39 | measurementsChanged(); 40 | } 41 | 42 | public float getTemperature() { return temperature; } 43 | public float getHumidity() { return humidity; } 44 | public float getPressure() { return pressure; } 45 | } -------------------------------------------------------------------------------- /java/observer/weather/WeatherStation.java: -------------------------------------------------------------------------------- 1 | public class WeatherStation { 2 | public static void main(String[] args) { 3 | WeatherData weatherData = new WeatherData(); 4 | 5 | CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData); 6 | StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 7 | ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 8 | HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData); 9 | 10 | weatherData.setMeasurements(80, 65, 30.4f); 11 | weatherData.setMeasurements(82, 70, 29.2f); 12 | weatherData.setMeasurements(78, 90, 29.2f); 13 | } 14 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/CurrentConditionsDisplay.java: -------------------------------------------------------------------------------- 1 | import java.util.Observable; 2 | import java.util.Observer; 3 | 4 | public class CurrentConditionsDisplay implements Observer, DisplayElement { 5 | Observable observable; 6 | private float temperature; 7 | private float humidity; 8 | 9 | public CurrentConditionsDisplay(Observable observable) { 10 | this.observable = observable; 11 | observable.addObserver(this); 12 | } 13 | 14 | public void update(Observable obs, Object args) { 15 | if (obs instanceof WeatherData) { 16 | WeatherData weatherData = (WeatherData)obs; 17 | this.temperature = weatherData.getTemperature(); 18 | this.humidity = weatherData.getHumidity(); 19 | display(); 20 | } 21 | } 22 | 23 | public void display() { 24 | System.out.println("Current conditions: " + temperature 25 | + "F degrees and " + humidity + "% humidity"); 26 | } 27 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/DisplayElement.java: -------------------------------------------------------------------------------- 1 | public interface DisplayElement { 2 | public void display(); 3 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/ForecastDisplay.java: -------------------------------------------------------------------------------- 1 | import java.util.Observable; 2 | import java.util.Observer; 3 | 4 | public class ForecastDisplay implements Observer, DisplayElement { 5 | Observable observable; 6 | private float currentPressure = 29.92f; 7 | private float lastPressure; 8 | 9 | public ForecastDisplay(Observable observable) { 10 | this.observable = observable; 11 | observable.addObserver(this); 12 | } 13 | 14 | public void update(Observable obs, Object args) { 15 | if (obs instanceof WeatherData) { 16 | WeatherData weatherData = (WeatherData)obs; 17 | lastPressure = currentPressure; 18 | currentPressure = weatherData.getPressure(); 19 | display(); 20 | } 21 | } 22 | 23 | public void display() { 24 | System.out.print("Forecast: "); 25 | if (currentPressure > lastPressure) { 26 | System.out.println("Improving weather on the way!"); 27 | } else if (currentPressure == lastPressure) { 28 | System.out.println("More of the same"); 29 | } else if (currentPressure < lastPressure) { 30 | System.out.println("Watch out for cooler, rainy weather"); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/HeatIndexDisplay.java: -------------------------------------------------------------------------------- 1 | import java.util.Observable; 2 | import java.util.Observer; 3 | 4 | public class HeatIndexDisplay implements Observer, DisplayElement { 5 | Observable observable; 6 | float heatIndex = 0.0f; 7 | 8 | public HeatIndexDisplay(Observable observable) { 9 | this.observable = observable; 10 | observable.addObserver(this); 11 | } 12 | 13 | public void update(Observable observable, Object arg) { 14 | if (observable instanceof WeatherData) { 15 | WeatherData weatherData = (WeatherData)observable; 16 | float t = weatherData.getTemperature(); 17 | float rh = weatherData.getHumidity(); 18 | heatIndex = (float) 19 | ( 20 | (16.923 + (0.185212 * t)) + 21 | (5.37941 * rh) - 22 | (0.100254 * t * rh) + 23 | (0.00941695 * (t * t)) + 24 | (0.00728898 * (rh * rh)) + 25 | (0.000345372 * (t * t * rh)) - 26 | (0.000814971 * (t * rh * rh)) + 27 | (0.0000102102 * (t * t * rh * rh)) - 28 | (0.000038646 * (t * t * t)) + 29 | (0.0000291583 * (rh * rh * rh)) + 30 | (0.00000142721 * (t * t * t * rh)) + 31 | (0.000000197483 * (t * rh * rh * rh)) - 32 | (0.0000000218429 * (t * t * t * rh * rh)) + 33 | (0.000000000843296 * (t * t * rh * rh * rh)) - 34 | (0.0000000000481975 * (t * t * t * rh * rh * rh))); 35 | display(); 36 | } 37 | } 38 | 39 | public void display() { 40 | System.out.println("Heat index is " + heatIndex); 41 | } 42 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/StatisticsDisplay.java: -------------------------------------------------------------------------------- 1 | import java.util.Observable; 2 | import java.util.Observer; 3 | 4 | public class StatisticsDisplay implements Observer, DisplayElement { 5 | Observable observable; 6 | private float maxTemp = 0.0f; 7 | private float minTemp = 200; 8 | private float tempSum= 0.0f; 9 | private int numReadings; 10 | 11 | public StatisticsDisplay(Observable observable) { 12 | this.observable = observable; 13 | observable.addObserver(this); 14 | } 15 | 16 | public void update(Observable obs, Object args) { 17 | if (obs instanceof WeatherData) { 18 | WeatherData weatherData = (WeatherData)obs; 19 | float temp = weatherData.getTemperature(); 20 | tempSum += temp; 21 | numReadings++; 22 | 23 | if (temp > maxTemp) { 24 | maxTemp = temp; 25 | } 26 | 27 | if (temp < minTemp) { 28 | minTemp = temp; 29 | } 30 | 31 | display(); 32 | } 33 | } 34 | 35 | public void display() { 36 | System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings) 37 | + "/" + maxTemp + "/" + minTemp); 38 | } 39 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/WeatherData.java: -------------------------------------------------------------------------------- 1 | import java.util.Observable; 2 | import java.util.Observer; 3 | 4 | public class WeatherData extends Observable { 5 | private float temperature; 6 | private float humidity; 7 | private float pressure; 8 | 9 | public WeatherData(){ } 10 | 11 | public void measurementsChanged() { 12 | setChanged(); 13 | notifyObservers(); 14 | } 15 | 16 | public void setMeasurements(float temperature, float humidity, float pressure) { 17 | this.temperature = temperature; 18 | this.humidity = humidity; 19 | this.pressure = pressure; 20 | measurementsChanged(); 21 | } 22 | 23 | public float getTemperature() { 24 | return temperature; 25 | } 26 | 27 | public float getHumidity() { 28 | return humidity; 29 | } 30 | 31 | public float getPressure() { 32 | return pressure; 33 | } 34 | } -------------------------------------------------------------------------------- /java/observer/weatherobservable/WeatherStation.java: -------------------------------------------------------------------------------- 1 | public class WeatherStation { 2 | 3 | public static void main(String[] args) { 4 | WeatherData weatherData = new WeatherData(); 5 | CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData); 6 | StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 7 | ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 8 | HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData); 9 | 10 | weatherData.setMeasurements(80, 65, 30.4f); 11 | weatherData.setMeasurements(82, 70, 29.2f); 12 | weatherData.setMeasurements(78, 90, 29.2f); 13 | } 14 | } -------------------------------------------------------------------------------- /java/proxy/gumball/GumballMachineRemote.java: -------------------------------------------------------------------------------- 1 | import java.rmi.*; 2 | 3 | public interface GumballMachineRemote extends Remote { 4 | public int getCount() throws RemoteException; 5 | public String getLocation() throws RemoteException; 6 | public State getState() throws RemoteException; 7 | } -------------------------------------------------------------------------------- /java/proxy/gumball/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.rmi.*; 2 | 3 | public class GumballMachineTestDrive { 4 | 5 | public static void main(String[] args) { 6 | GumballMachine gumballMachine = null; 7 | int count; 8 | if (args.length < 2) { 9 | System.out.println("GumballMachine "); 10 | System.exit(1); 11 | } 12 | 13 | try { 14 | count = Integer.parseInt(args[1]); 15 | gumballMachine = new GumballMachine(args[0], count); 16 | Naming.rebind("//" + args[0] + "/gumballmachine", gumballMachine); 17 | } 18 | catch (Exception e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /java/proxy/gumball/GumballMonitor.java: -------------------------------------------------------------------------------- 1 | import java.rmi.*; 2 | 3 | public class GumballMonitor { 4 | GumballMachineRemote machine; 5 | 6 | public GumballMonitor(GumballMachineRemote machine) { 7 | this.machine = machine; 8 | } 9 | 10 | public void report() { 11 | try { 12 | System.out.println("Gumball Machine: " + machine.getLocation()); 13 | System.out.println("Current inventory: " + machine.getCount() + "gumballs"); 14 | System.out.println("Current state: " + machine.getState()); 15 | } 16 | catch (RemoteException e) { 17 | e.printStackTrace(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /java/proxy/gumball/GumballMonitorTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.rmi.*; 2 | 3 | public class GumballMonitorTestDrive { 4 | 5 | public static void main(String[] args) { 6 | String[] location = { "rmi://santafe.mightygumball.com/gumballmachine", 7 | "rmi://boulder.mightygumball.com/gumballmachine", 8 | "rmi://seattle.mightygumball.com/gumballmachine"); 9 | 10 | GumballMonitor[] monitor = new GumballMonitor[location.length]; 11 | 12 | for (int i = 0; i < location.length; i++) { 13 | try { 14 | GumballMachineRemote machine = (GumballMachineRemote)Naming.lookup(location[i]); 15 | monitor[i] = new GumballMonitor(machine); 16 | System.out.println(monitor[i]); 17 | } 18 | catch (Exception e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | for (int i = 0; i monitor.length; i++) { 24 | monitor[i].report(); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /java/proxy/gumball/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class HasQuarterState implements State { 4 | transient GumballMachine gumballMachine; 5 | Random randomWinner = new Random(System.currentTimeMillis()); 6 | 7 | public HasQuarterState(GumballMachine gumballMachine) { 8 | this.gumballMachine = gumballMachine; 9 | } 10 | 11 | public void insertQuarter() { 12 | System.out.println("You can't insert another quarter"); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("Quarter returned"); 17 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 18 | } 19 | 20 | public void turnCrank() { 21 | System.out.println("You turned..."); 22 | int winner = randomWinner.nextInt(10); 23 | if ((winner == 0) && (gumballMachine.getCount() > 1)) { 24 | gumballMachine.setState(gumballMachine.getWinnerState()); 25 | } 26 | else { 27 | gumballMachine.setState(gumballMachine.getSoldState()); 28 | } 29 | } 30 | 31 | public void dispense() { 32 | System.out.println("No gumball dispensed"); 33 | } 34 | 35 | public String toString() { 36 | return "waiting for turn of crank"; 37 | } 38 | } -------------------------------------------------------------------------------- /java/proxy/gumball/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | public class NoQuarterState implements State { 2 | transient GumballMachine gumballMachine; 3 | 4 | public NoQuarterState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You inserted a quarter"); 10 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 11 | } 12 | 13 | public void ejectQuarter() { 14 | System.out.println("You haven't inserted a quarter"); 15 | } 16 | 17 | public void turnCrank() { 18 | System.out.println("You turned, but there's no quarter"); 19 | } 20 | 21 | public void dispense() { 22 | System.out.println("You need to pay first"); 23 | } 24 | 25 | public String toString() { 26 | return "waiting for quarter"; 27 | } 28 | } -------------------------------------------------------------------------------- /java/proxy/gumball/SoldOutState.java: -------------------------------------------------------------------------------- 1 | public class SoldOutState implements State { 2 | transient GumballMachine gumballMachine; 3 | 4 | public SoldOutState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You can't insert a quarter, the machine is sold out"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("You turned, but there are no gumballs"); 18 | } 19 | 20 | public void dispense() { 21 | System.out.println("No gumball dispensed"); 22 | } 23 | 24 | public String toString() { 25 | return "sold out"; 26 | } 27 | } -------------------------------------------------------------------------------- /java/proxy/gumball/SoldState.java: -------------------------------------------------------------------------------- 1 | public class SoldState implements State { 2 | transient GumballMachine gumballMachine; 3 | 4 | public SoldState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("Please wait, we're already giving you a gumball"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("Sorry, you already turned the crank"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("Turning twice doesn't get you another gumball!"); 18 | } 19 | 20 | public void dispense() { 21 | gumballMachine.releaseBall(); 22 | if (gumballMachine.getCount() > 0) { 23 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 24 | } 25 | else { 26 | System.out.println("Oops, out of gumballs now!"); 27 | gumballMachine.setState(gumballMachine.getSoldOutState()); 28 | } 29 | } 30 | 31 | public String toString() { 32 | return "dispensing a gumball"; 33 | } 34 | } -------------------------------------------------------------------------------- /java/proxy/gumball/State.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public interface State extends Serializable { 4 | public void insertQuarter(); 5 | public void ejectQuarter(); 6 | public void turnCrank(); 7 | public void dispense(); 8 | } -------------------------------------------------------------------------------- /java/proxy/gumball/WinnerState.java: -------------------------------------------------------------------------------- 1 | public class WinnerState implements State { 2 | transient GumballMachine gumballMachine; 3 | 4 | public WinnerState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("Please wait, we're already giving you a Gumball"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("Please wait, we're already giving you a Gumball"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("Turning again doesn't get you another gumball!"); 18 | } 19 | 20 | public void dispense() { 21 | System.out.println("YOU'RE A WINNER! You get two gumballs for your quarter"); 22 | gumballMachine.releaseBall(); 23 | if (gumballMachine.getCount() == 0) { 24 | System.out.println("Oops, out of gumballs!"); 25 | gumballMachine.setState(gumballMachine.getSoldOutState()); 26 | } else { 27 | gumballMachine.releaseBall(); 28 | if (gumballMachine.getCount() > 0) { 29 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 30 | } else { 31 | System.out.println("Oops, out of gumballs!"); 32 | gumballMachine.setState(gumballMachine.getSoldOutState()); 33 | } 34 | } 35 | } 36 | 37 | public String toString() { 38 | return "despensing two gumballs for your quarter, because YOU'RE A WINNER!"; 39 | } 40 | } -------------------------------------------------------------------------------- /java/proxy/javaproxy/NonOwnerInvocationHandler.java: -------------------------------------------------------------------------------- 1 | import java.lang.reflect.*; 2 | 3 | public class NonOwnerInvocationHandler implements InvocationHandler { 4 | PersonBean person; 5 | 6 | public NonOwnerInvocationHandler(PersonBean person) { 7 | this.person = person; 8 | } 9 | 10 | public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException { 11 | try { 12 | if (method.getName().startsWith("get")) { 13 | return method.invoke(person, args); 14 | } 15 | else if (method.getName().equals("setHotOrNotRating")) { 16 | return method.invoke(person, args); 17 | } 18 | else if (method.getName().startsWith("set")) { 19 | throw new IllegalAccessException(); 20 | } 21 | } 22 | catch (InvocationTargetException e) { 23 | e.printStackTrace(); 24 | } 25 | return null; 26 | } 27 | } -------------------------------------------------------------------------------- /java/proxy/javaproxy/OwnerInvocationHandler.java: -------------------------------------------------------------------------------- 1 | import java.lang.reflect.*; 2 | 3 | public class OwnerInvocationHandler implements InvocationHandler { 4 | PersonBean person; 5 | 6 | public OwnerInvocationHandler(PersonBean person) { 7 | this.person = person; 8 | } 9 | 10 | public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException { 11 | try { 12 | if (method.getName().startsWith("get")) { 13 | return method.invoke(person, args); 14 | } 15 | else if (method.getName().equals("setHotOrNotRating")) { 16 | throw new IllegalAccessException(); 17 | } 18 | else if (method.getName().startsWith("set")) { 19 | return method.invoke(person, args); 20 | } 21 | } 22 | catch (InvocationTargetException e) { 23 | e.printStackTrace(); 24 | } 25 | return null; 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /java/proxy/javaproxy/PersonBean.java: -------------------------------------------------------------------------------- 1 | public interface PersonBean { 2 | String getName(); 3 | String getGender(); 4 | String getInterests(); 5 | int getHotOrNotRating(); 6 | 7 | void setName(String name); 8 | void setGender(String gender); 9 | void setInterests(String interests); 10 | void setHotOrNotRating(int rating); 11 | } -------------------------------------------------------------------------------- /java/proxy/javaproxy/PersonBeanImpl.java: -------------------------------------------------------------------------------- 1 | public class PersonBeanImpl implements PersonBean { 2 | String name; 3 | String gender; 4 | String interests; 5 | int rating; 6 | int ratingCount = 0; 7 | 8 | public String getName() { return name;} 9 | public String getGender() { return gender;} 10 | public String getInterests() { return interests;} 11 | 12 | public int getHotOrNotRating() { 13 | if (ratingCount == 0) { 14 | return 0; 15 | } 16 | else { 17 | return (rating/ratingCount); 18 | } 19 | } 20 | 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | 25 | public void setGender(String gender) { 26 | this.gender = gender; 27 | } 28 | 29 | public void setInterests(String interests) { 30 | this.interests = interests; 31 | } 32 | 33 | public void setHotOrNotRating(int rating) { 34 | this.rating += rating; 35 | ratingCount++; 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /java/proxy/virtualproxy/ImageComponent.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import javax.swing.*; 3 | 4 | class ImageComponent extends JComponent { 5 | private Icon icon; 6 | 7 | public ImageComponent(Icon icon) { 8 | this.icon = icon; 9 | } 10 | 11 | public void setIcon(Icon icon) { 12 | this.icon = icon; 13 | } 14 | 15 | public void paintComponent(Graphics g) { 16 | super.paintComponent(g); 17 | int w = icon.getIconWidth(); 18 | int h = icon.getIconHeight(); 19 | int x = (800 - w)/2; 20 | int y = (600 - h)/2; 21 | icon.paintIcon(this, g, x, y); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/proxy/virtualproxy/ImageProxy.java: -------------------------------------------------------------------------------- 1 | import java.net.*; 2 | import java.awt.*; 3 | import java.awt.event.*; 4 | import javax.swing.*; 5 | 6 | class ImageProxy implements Icon { 7 | ImageIcon imageIcon; 8 | URL imageURL; 9 | Thread retrievalThread; 10 | boolean retrieving = false; 11 | 12 | public ImageProxy(URL url) { imageURL = url;} 13 | 14 | public int getIconWidth() { 15 | if (imageIcon != null) { 16 | return imageIcon.getIconWidth(); 17 | } 18 | else { 19 | return 800; 20 | } 21 | } 22 | 23 | public int getIconHeight() { 24 | if (imageIcon != null) { 25 | return imageIcon.getIconHeight(); 26 | } 27 | else { 28 | return 600; 29 | } 30 | } 31 | 32 | public void paintIcon(final Component c, Graphics g, int x, int y) { 33 | if (imageIcon != null) { 34 | imageIcon.paintIcon(c, g, x, y); 35 | } 36 | else { 37 | g.drawString("Loading CD cover, please wait...", x + 300, y + 190); 38 | if (!retrieving) { 39 | retrieving = true; 40 | retrievalThread = new Thread(new Runnable() { 41 | public void run() { 42 | try { 43 | imageIcon = new ImageIcon(imageURL, "CD Cover"); 44 | c.repaint(); 45 | } 46 | catch (Exception e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | }); 51 | retrievalThread.start(); 52 | } 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /java/singleton/classic/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | 3 | private static Singleton uniqueInstance; 4 | 5 | private Singleton() {} 6 | 7 | public static Singleton getInstance() { 8 | if (uniqueInstance == null) { 9 | uniqueInstance = new Singleton(); 10 | } 11 | return uniqueInstance; 12 | } 13 | } 14 | 15 | // Not thread safe. 16 | -------------------------------------------------------------------------------- /java/singleton/doublecheckedlocking/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | 3 | private volatile static Singleton uniqueInstance; 4 | 5 | private Singleton() {} 6 | 7 | public static Singleton getInstance() { 8 | if (uniqueInstance == null) { 9 | synchronized (Single.class) { 10 | if (uniqueInstance == null) { 11 | uniqueInstance = new Singleton(); 12 | } 13 | } 14 | } 15 | } 16 | } 17 | 18 | // Only synchronize the first time through. -------------------------------------------------------------------------------- /java/singleton/static/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | 3 | private static Singleton uniqueInstance = new Singleton(); 4 | 5 | private Singleton() {} 6 | 7 | public static Singleton getInstance() { 8 | return uniqueInstance; 9 | } 10 | } 11 | 12 | /* 13 | If your application always creates and uses an instance of the Singleton 14 | or the overhead of creation and runtime aspects of the Singleton are not 15 | onerous, this can create your Singleton eagerly. 16 | */ 17 | -------------------------------------------------------------------------------- /java/singleton/static/SingletonClient.java: -------------------------------------------------------------------------------- 1 | public class SingletonClient { 2 | 3 | public static void main(String[] args) { 4 | Singleton singleton = Singleton.getInstance(); 5 | } 6 | } -------------------------------------------------------------------------------- /java/singleton/subclass/CoolerSingleton.java: -------------------------------------------------------------------------------- 1 | public class CoolerSingleton extends Singleton { 2 | 3 | protected static Singleton uniqueInstance; 4 | 5 | private CoolerSingleton() { 6 | super(); 7 | } 8 | } -------------------------------------------------------------------------------- /java/singleton/subclass/HotterSingleton.java: -------------------------------------------------------------------------------- 1 | public class HotterSingleton extends Singleton { 2 | 3 | protected static Singleton uniqueInstance; 4 | 5 | private HotterSingleton() { 6 | super(); 7 | } 8 | } -------------------------------------------------------------------------------- /java/singleton/subclass/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | 3 | protected static Singleton uniqueInstance; 4 | 5 | protected Singleton () {} 6 | 7 | public static synchronized Singleton getInstance() { 8 | if (uniqueInstance == null) { 9 | uniqueInstance = new Singleton(); 10 | } 11 | return uniqueInstance; 12 | } 13 | } -------------------------------------------------------------------------------- /java/singleton/subclass/SingletonTestDrive.java: -------------------------------------------------------------------------------- 1 | public class SingletonTestDrive { 2 | 3 | public static void main(String[] args) { 4 | Singleton foo = CoolerSingleton.getInstance(); 5 | Singleton bar = HotterSingleton.getInstance(); 6 | System.out.println(foo); 7 | System.out.println(bar); 8 | } 9 | } 10 | 11 | // 'foo' and 'bar' are the same object here. -------------------------------------------------------------------------------- /java/singleton/threadsafe/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | 3 | private static Singleton uniqueInstance; 4 | 5 | private Singleton() {} 6 | 7 | public static synchronized Singleton getInstance() { 8 | if (uniqueInstance == null) { 9 | uniqueInstance = new Singleton(); 10 | } 11 | return uniqueInstance; 12 | } 13 | } 14 | 15 | /* 16 | Synchronization is expensive and there is totally 17 | unneeded overhead after the first time through. 18 | */ -------------------------------------------------------------------------------- /java/state/gumball/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | public class GumballMachineTestDrive { 2 | 3 | public static void main(String[] args) { 4 | GumballMachine gumballMachine = new GumballMachine(5); 5 | 6 | System.out.println(gumballMachine); 7 | 8 | gumballMachine.insertQuarter(); 9 | gumballMachine.turnCrank(); 10 | 11 | System.out.println(gumballMachine); 12 | 13 | gumballMachine.insertQuarter(); 14 | gumballMachine.ejectQuarter(); 15 | gumballMachine.turnCrank(); 16 | 17 | System.out.println(gumballMachine); 18 | 19 | gumballMachine.insertQuarter(); 20 | gumballMachine.turnCrank(); 21 | gumballMachine.insertQuarter(); 22 | gumballMachine.turnCrank(); 23 | gumballMachine.ejectQuarter(); 24 | 25 | System.out.println(gumballMachine); 26 | 27 | gumballMachine.insertQuarter(); 28 | gumballMachine.insertQuarter(); 29 | gumballMachine.turnCrank(); 30 | gumballMachine.insertQuarter(); 31 | gumballMachine.turnCrank(); 32 | gumballMachine.insertQuarter(); 33 | gumballMachine.turnCrank(); 34 | 35 | System.out.println(gumballMachine); 36 | } 37 | } -------------------------------------------------------------------------------- /java/state/gumballstate/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | public class GumballMachineTestDrive { 2 | 3 | public static void main(String[] args) { 4 | GumballMachine gumballMachine = new GumballMachine(5); 5 | 6 | System.out.println(gumballMachine); 7 | 8 | gumballMachine.insertQuarter(); 9 | gumballMachine.turnCrank(); 10 | 11 | System.out.println(gumballMachine); 12 | 13 | gumballMachine.insertQuarter(); 14 | gumballMachine.turnCrank(); 15 | gumballMachine.insertQuarter(); 16 | gumballMachine.turnCrank(); 17 | 18 | System.out.println(gumballMachine); 19 | } 20 | } -------------------------------------------------------------------------------- /java/state/gumballstate/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | public class HasQuarterState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public HasQuarterState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You can't insert another quarter"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("Quarter returned"); 14 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 15 | } 16 | 17 | public void turnCrank() { 18 | System.out.println("You turned..."); 19 | gumballMachine.setState(gumballMachine.getSoldState()); 20 | } 21 | 22 | public void dispense() { 23 | System.out.println("No gumball dispensed"); 24 | } 25 | 26 | public String toString() { 27 | return "waiting for turn of crank"; 28 | } 29 | } -------------------------------------------------------------------------------- /java/state/gumballstate/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | public class NoQuarterState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public NoQuarterState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You inserted a quarter"); 10 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 11 | } 12 | 13 | public void ejectQuarter() { 14 | System.out.println("You haven't inserted a quarter"); 15 | } 16 | 17 | public void turnCrank() { 18 | System.out.println("You turned, but there's no quarter"); 19 | } 20 | 21 | public void dispense() { 22 | System.out.println("You need to pay first"); 23 | } 24 | 25 | public String toString() { 26 | return "waiting for quarter"; 27 | } 28 | } -------------------------------------------------------------------------------- /java/state/gumballstate/SoldOutState.java: -------------------------------------------------------------------------------- 1 | public class SoldOutState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public SoldOutState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You can't insert a quarter, the machine is sold out"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("You turned, but there are no gumballs"); 18 | } 19 | 20 | public void dispense() { 21 | System.out.println("No gumball dispensed"); 22 | } 23 | 24 | public String toString() { 25 | return "sold out"; 26 | } 27 | } -------------------------------------------------------------------------------- /java/state/gumballstate/SoldState.java: -------------------------------------------------------------------------------- 1 | public class SoldState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public SoldState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("Please wait, we're already giving you a gumball"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("Sorry, you already turned the crank"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("Turning twice doesn't get you another gumball!"); 18 | } 19 | 20 | public void dispense() { 21 | gumballMachine.releaseBall(); 22 | if (gumballMachine.getCount() > 0) { 23 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 24 | } 25 | else { 26 | System.out.println("Oops, out of gumballs now!"); 27 | gumballMachine.setState(gumballMachine.getSoldOutState()); 28 | } 29 | } 30 | 31 | public String toString() { 32 | return "dispensing a gumball"; 33 | } 34 | } -------------------------------------------------------------------------------- /java/state/gumballstate/State.java: -------------------------------------------------------------------------------- 1 | public interface State { 2 | public void insertQuarter(); 3 | public void ejectQuarter(); 4 | public void turnCrank(); 5 | public void dispense(); 6 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | public class GumballMachineTestDrive { 2 | 3 | public static void main(String[] args) { 4 | GumballMachine gumballMachine = new GumballMachine(5); 5 | 6 | System.out.println(gumballMachine); 7 | 8 | gumballMachine.insertQuarter(); 9 | gumballMachine.turnCrank(); 10 | 11 | System.out.println(gumballMachine); 12 | 13 | gumballMachine.insertQuarter(); 14 | gumballMachine.turnCrank(); 15 | gumballMachine.insertQuarter(); 16 | gumballMachine.turnCrank(); 17 | 18 | System.out.println(gumballMachine); 19 | } 20 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class HasQuarterState implements State { 4 | GumballMachine gumballMachine; 5 | Random randomWinner = new Random(System.currentTimeMillis()); 6 | 7 | public HasQuarterState(GumballMachine gumballMachine) { 8 | this.gumballMachine = gumballMachine; 9 | } 10 | 11 | public void insertQuarter() { 12 | System.out.println("You can't insert another quarter"); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("Quarter returned"); 17 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 18 | } 19 | 20 | public void turnCrank() { 21 | System.out.println("You turned..."); 22 | int winner = randomWinner.nextInt(10); 23 | if ((winner == 0) && (gumballMachine.getCount() > 1)) { 24 | gumballMachine.setState(gumballMachine.getWinnerState()); 25 | } 26 | else { 27 | gumballMachine.setState(gumballMachine.getSoldState()); 28 | } 29 | } 30 | 31 | public void dispense() { 32 | System.out.println("No gumball dispensed"); 33 | } 34 | 35 | public String toString() { 36 | return "waiting for turn of crank"; 37 | } 38 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | public class NoQuarterState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public NoQuarterState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You inserted a quarter"); 10 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 11 | } 12 | 13 | public void ejectQuarter() { 14 | System.out.println("You haven't inserted a quarter"); 15 | } 16 | 17 | public void turnCrank() { 18 | System.out.println("You turned, but there's no quarter"); 19 | } 20 | 21 | public void dispense() { 22 | System.out.println("You need to pay first"); 23 | } 24 | 25 | public String toString() { 26 | return "waiting for quarter"; 27 | } 28 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/SoldOutState.java: -------------------------------------------------------------------------------- 1 | public class SoldOutState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public SoldOutState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("You can't insert a quarter, the machine is sold out"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("You turned, but there are no gumballs"); 18 | } 19 | 20 | public void dispense() { 21 | System.out.println("No gumball dispensed"); 22 | } 23 | 24 | public String toString() { 25 | return "sold out"; 26 | } 27 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/SoldState.java: -------------------------------------------------------------------------------- 1 | public class SoldState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public SoldState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("Please wait, we're already giving you a gumball"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("Sorry, you already turned the crank"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("Turning twice doesn't get you another gumball!"); 18 | } 19 | 20 | public void dispense() { 21 | gumballMachine.releaseBall(); 22 | if (gumballMachine.getCount() > 0) { 23 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 24 | } 25 | else { 26 | System.out.println("Oops, out of gumballs now!"); 27 | gumballMachine.setState(gumballMachine.getSoldOutState()); 28 | } 29 | } 30 | 31 | public String toString() { 32 | return "dispensing a gumball"; 33 | } 34 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/State.java: -------------------------------------------------------------------------------- 1 | public interface State { 2 | public void insertQuarter(); 3 | public void ejectQuarter(); 4 | public void turnCrank(); 5 | public void dispense(); 6 | } -------------------------------------------------------------------------------- /java/state/gumballstatewinner/WinnerState.java: -------------------------------------------------------------------------------- 1 | public class WinnerState implements State { 2 | GumballMachine gumballMachine; 3 | 4 | public WinnerState(GumballMachine gumballMachine) { 5 | this.gumballMachine = gumballMachine; 6 | } 7 | 8 | public void insertQuarter() { 9 | System.out.println("Please wait, we're already giving you a Gumball"); 10 | } 11 | 12 | public void ejectQuarter() { 13 | System.out.println("Please wait, we're already giving you a Gumball"); 14 | } 15 | 16 | public void turnCrank() { 17 | System.out.println("Turning again doesn't get you another gumball!"); 18 | } 19 | 20 | public void dispense() { 21 | System.out.println("YOU'RE A WINNER! You get two gumballs for your quarter"); 22 | gumballMachine.releaseBall(); 23 | if (gumballMachine.getCount() == 0) { 24 | System.out.println("Oops, out of gumballs!"); 25 | gumballMachine.setState(gumballMachine.getSoldOutState()); 26 | } else { 27 | gumballMachine.releaseBall(); 28 | if (gumballMachine.getCount() > 0) { 29 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 30 | } else { 31 | System.out.println("Oops, out of gumballs!"); 32 | gumballMachine.setState(gumballMachine.getSoldOutState()); 33 | } 34 | } 35 | } 36 | 37 | public String toString() { 38 | return "despensing two gumballs for your quarter, because YOU'RE A WINNER!"; 39 | } 40 | } -------------------------------------------------------------------------------- /java/strategy/Duck.java: -------------------------------------------------------------------------------- 1 | public abstract class Duck { 2 | FlyBehavior flyBehavior; 3 | QuackBehavior quackBehavior; 4 | 5 | public Duck() { 6 | } 7 | 8 | public abstract void display(); 9 | 10 | public void performFly() { 11 | flyBehavior.fly(); 12 | } 13 | 14 | public void performQuack() { 15 | quackBehavior.quack(); 16 | } 17 | 18 | public void setFlyBehavior(FlyBehavior fb) { 19 | flyBehavior = fb; 20 | } 21 | 22 | public void setQuackBehavior(QuackBehavior qb) { 23 | quackBehavior = qb; 24 | } 25 | 26 | public void swim() { 27 | System.out.println("All ducks float, even decoys!"); 28 | } 29 | } -------------------------------------------------------------------------------- /java/strategy/FlyBehavior.java: -------------------------------------------------------------------------------- 1 | public interface FlyBehavior { 2 | public void fly(); 3 | } -------------------------------------------------------------------------------- /java/strategy/FlyNoWay.java: -------------------------------------------------------------------------------- 1 | public class FlyNoWay implements FlyBehavior { 2 | public void fly() { 3 | System.out.println("I can't fly."); 4 | } 5 | } -------------------------------------------------------------------------------- /java/strategy/FlyRocketPowered.java: -------------------------------------------------------------------------------- 1 | public class FlyRocketPowered implements FlyBehavior { 2 | public void fly() { 3 | System.out.println("I'm flying with a rocket!"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/strategy/FlyWithWings.java: -------------------------------------------------------------------------------- 1 | public class FlyWithWings implements FlyBehavior { 2 | public void fly() { 3 | System.out.println("I'm flying!!"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/strategy/MallardDuck.java: -------------------------------------------------------------------------------- 1 | public class MallardDuck extends Duck { 2 | public MallardDuck() { 3 | quackBehavior = new Quack(); 4 | flyBehavior = new FlyWithWings(); 5 | } 6 | 7 | public void display() { 8 | System.out.println("I'm a real Mallard duck"); 9 | } 10 | } -------------------------------------------------------------------------------- /java/strategy/MiniDuckSimulator.java: -------------------------------------------------------------------------------- 1 | public class MiniDuckSimulator { 2 | public static void main(String[] args) { 3 | Duck mallard = new MallardDuck(); 4 | mallard.performQuack(); // Quack 5 | mallard.performFly(); // I'm flying!! 6 | 7 | Duck model = new ModelDuck(); 8 | model.performFly(); // I can't fly 9 | model.setFlyBehavior(new FlyRocketPowered()); 10 | model.performFly(); // I'm flying with a rocket 11 | } 12 | } -------------------------------------------------------------------------------- /java/strategy/ModelDuck.java: -------------------------------------------------------------------------------- 1 | public class ModelDuck extends Duck { 2 | public ModelDuck(){ 3 | flyBehavior = new FlyNoWay(); 4 | quackBehavior = new Quack(); 5 | } 6 | 7 | public void display() { 8 | System.out.println("I'm a model duck"); 9 | } 10 | } -------------------------------------------------------------------------------- /java/strategy/MuteQuack.java: -------------------------------------------------------------------------------- 1 | public class MuteQuack implements QuackBehavior { 2 | public void quack() { 3 | System.out.println("<< Silence >>"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/strategy/Quack.java: -------------------------------------------------------------------------------- 1 | public class Quack implements QuackBehavior { 2 | public void quack() { 3 | System.out.println("Quack"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/strategy/QuackBehavior.java: -------------------------------------------------------------------------------- 1 | public interface QuackBehavior { 2 | public void quack(); 3 | } -------------------------------------------------------------------------------- /java/strategy/Squeak.java: -------------------------------------------------------------------------------- 1 | public class Squeak implements QuackBehavior { 2 | public void quack() { 3 | System.out.println("Squeak"); 4 | } 5 | } -------------------------------------------------------------------------------- /java/templatemethod/applet/MyApplet.java: -------------------------------------------------------------------------------- 1 | import java.applet.Applet; 2 | import java.awt.Graphics; 3 | 4 | public class MyApplet extends Applet { 5 | String message; 6 | 7 | public void init() { 8 | message = "Hello World, I'm alive!"; 9 | repaint(); 10 | } 11 | 12 | public void start() { 13 | message = "Now I'm starting up..."; 14 | repaint(); 15 | } 16 | 17 | public void stop() { 18 | message = "Oh, now I'm being stopped..."; 19 | repaint(); 20 | } 21 | 22 | public void destroy() { 23 | message = "Goodbye, cruel world"; 24 | repaint(); 25 | } 26 | 27 | public void paint(Graphics g) { 28 | g.drawString(message, 5, 15); 29 | } 30 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/BeverageTestDrive.java: -------------------------------------------------------------------------------- 1 | public class BeverageTestDrive { 2 | 3 | public static void main(String[] args) { 4 | Tea tea = new Tea(); 5 | Coffee coffee = new Coffee(); 6 | 7 | System.out.println("\nMaking tea..."); 8 | tea.prepareRecipe(); 9 | 10 | System.out.println("\nMaking coffee..."); 11 | coffee.prepareRecipe(); 12 | 13 | TeaWithHook teaWithHook = new TeaWithHook(); 14 | CoffeeWithHook coffeeWithHook = new CoffeeWithHook(); 15 | 16 | System.out.println("\nMaking tea..."); 17 | teaWithHook.prepareRecipe(); 18 | 19 | System.out.println("\nMaking coffee..."); 20 | coffeeWithHook.prepareRecipe(); 21 | } 22 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/CaffeineBeverage.java: -------------------------------------------------------------------------------- 1 | public abstract class CaffeineBeverage { 2 | 3 | public void prepareRecipe() { 4 | boilWater(); 5 | brew(); 6 | pourInCup(); 7 | addCondiments(); 8 | } 9 | 10 | abstract void brew(); 11 | 12 | abstract void addCondiments(); 13 | 14 | public void boilWater() { 15 | System.out.println("Boiling water"); 16 | } 17 | 18 | public void pourInCup() { 19 | System.out.println("Pouring into cup"); 20 | } 21 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/CaffeineBeverageWithHook.java: -------------------------------------------------------------------------------- 1 | public abstract class CaffeineBeverageWithHook { 2 | 3 | void prepareRecipe() { 4 | boilWater(); 5 | brew(); 6 | pourInCup(); 7 | if (customerWantsCondiments()) { 8 | addCondiments(); 9 | } 10 | } 11 | 12 | abstract void brew(); 13 | 14 | abstract void addCondiments(); 15 | 16 | void boilWater() { 17 | System.out.println("Boiling water"); 18 | } 19 | 20 | void pourInCup() { 21 | System.out.println("Pouring into cup"); 22 | } 23 | 24 | boolean customerWantsCondiments() { 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/Coffee.java: -------------------------------------------------------------------------------- 1 | public class Coffee extends CaffeineBeverage { 2 | 3 | public void brew() { 4 | System.out.println("Dripping Coffee through filter"); 5 | } 6 | 7 | public void addCondiments() { 8 | System.out.println("Adding Sugar and Milk"); 9 | } 10 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/CoffeeWithHook.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class CoffeeWithHook extends CaffeineBeverageWithHook { 4 | 5 | public void brew() { 6 | System.out.println("Dripping Coffee through filter"); 7 | } 8 | 9 | public void addCondiments() { 10 | System.out.println("Adding Sugar and Milk"); 11 | } 12 | 13 | public boolean customerWantsCondiments() { 14 | 15 | String answer = getUserInput(); 16 | 17 | if (answer.toLowerCase().startsWith("y")) { 18 | return true; 19 | } else { 20 | return false; 21 | } 22 | } 23 | 24 | private String getUserInput() { 25 | String answer = null; 26 | 27 | System.out.print("Would you like milk and sugar with your coffee (y/n)? "); 28 | 29 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 30 | try { 31 | answer = in.readLine(); 32 | } catch (IOException ioe) { 33 | System.err.println("IO error trying to read your answer"); 34 | } 35 | if (answer == null) { 36 | return "no"; 37 | } 38 | return answer; 39 | } 40 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/Tea.java: -------------------------------------------------------------------------------- 1 | public class Tea extends CaffeineBeverage { 2 | 3 | public void brew() { 4 | System.out.println("Steeping the tea"); 5 | } 6 | 7 | public void addCondiments() { 8 | System.out.println("Adding Lemon"); 9 | } 10 | } -------------------------------------------------------------------------------- /java/templatemethod/barista/TeaWithHook.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class TeaWithHook extends CaffeineBeverageWithHook { 4 | 5 | public void brew() { 6 | System.out.println("Steeping the tea"); 7 | } 8 | 9 | public void addCondiments() { 10 | System.out.println("Adding Lemon"); 11 | } 12 | 13 | public boolean customerWantsCondiments() { 14 | 15 | String answer = getUserInput(); 16 | 17 | if (answer.toLowerCase().startsWith("y")) { 18 | return true; 19 | } else { 20 | return false; 21 | } 22 | } 23 | 24 | private String getUserInput() { 25 | String answer = null; 26 | 27 | System.out.print("Would you like lemon with your tea (y/n)? "); 28 | 29 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 30 | try { 31 | answer = in.readLine(); 32 | } catch (IOException ioe) { 33 | System.err.println("IO error trying to read your answer"); 34 | } 35 | if (answer == null) { 36 | return "no"; 37 | } 38 | return answer; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /java/templatemethod/frame/MyFrame.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import javax.swing.*; 3 | 4 | public class MyFrame extends JFrame { 5 | 6 | public MyFrame(String title) { 7 | super(title); 8 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 9 | 10 | this.setSize(300,300); 11 | this.setVisible(true); 12 | } 13 | 14 | public void paint(Graphics graphics) { 15 | super.paint(graphics); 16 | String msg = "I rule!!"; 17 | graphics.drawString(msg, 100, 100); 18 | } 19 | 20 | public static void main(String[] args) { 21 | MyFrame myFrame = new MyFrame("Head First Design Patterns"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/templatemethod/simplebarista/Barista.java: -------------------------------------------------------------------------------- 1 | /* 2 | This design could be made better using the Template Method Pattern 3 | */ 4 | 5 | public class Barista { 6 | 7 | public static void main(String[] args) { 8 | Tea tea = new Tea(); 9 | Coffee coffee = new Coffee(); 10 | System.out.println("Making tea..."); 11 | tea.prepareRecipe(); 12 | System.out.println("Making coffee..."); 13 | coffee.prepareRecipe(); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /java/templatemethod/simplebarista/Coffee.java: -------------------------------------------------------------------------------- 1 | public class Coffee { 2 | 3 | void prepareRecipe() { 4 | boilWater(); 5 | brewCoffeeGrinds(); 6 | pourInCup(); 7 | addSugarAndMilk(); 8 | } 9 | 10 | public void boilWater() { 11 | System.out.println("Boiling water"); 12 | } 13 | 14 | public void brewCoffeeGrinds() { 15 | System.out.println("Dripping Coffee through filter"); 16 | } 17 | 18 | public void pourInCup() { 19 | System.out.println("Pouring into cup"); 20 | } 21 | 22 | public void addSugarAndMilk() { 23 | System.out.println("Adding Sugar and Milk"); 24 | } 25 | } -------------------------------------------------------------------------------- /java/templatemethod/simplebarista/Tea.java: -------------------------------------------------------------------------------- 1 | public class Tea { 2 | 3 | void prepareRecipe() { 4 | boilWater(); 5 | brewCoffeeGrinds(); 6 | pourInCup(); 7 | addLemon(); 8 | } 9 | 10 | public void boilWater() { 11 | System.out.println("Boiling water"); 12 | } 13 | 14 | public void brewCoffeeGrinds() { 15 | System.out.println("Steeping the tea"); 16 | } 17 | 18 | public void pourInCup() { 19 | System.out.println("Pouring into cup"); 20 | } 21 | 22 | public void addLemon() { 23 | System.out.println("Adding Lemon"); 24 | } 25 | } -------------------------------------------------------------------------------- /java/templatemethod/sort/Duck.java: -------------------------------------------------------------------------------- 1 | public class Duck implements Comparable { 2 | String name; 3 | int weight; 4 | 5 | public Duck(String name, int weight) { 6 | this.name = name; 7 | this.weight = weight; 8 | } 9 | 10 | public String toString() { 11 | return name + " weighs " + weight; 12 | } 13 | 14 | public int compareTo(Object object) { 15 | Duck otherDuck = (Duck)object; 16 | 17 | if (this.weight < otherDuck.weight) { 18 | return -1; 19 | } 20 | else if (this.weight == otherDuck.weight) { 21 | return 0; 22 | } 23 | else { 24 | return 1; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /java/templatemethod/sort/DuckSortTestDrive.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | 4 | public class DuckSortTestDrive { 5 | 6 | public static void main(String[] args) { 7 | Duck[] ducks = { 8 | new Duck("Daffy", 8), 9 | new Duck("Dewey", 2), 10 | new Duck("Howard", 7), 11 | new Duck("Louie", 2), 12 | new Duck("Donald", 10), 13 | new Duck("Huey", 2) 14 | }; 15 | 16 | System.out.println("Before sorting:"); 17 | display(ducks); 18 | 19 | Arrays.sort(ducks); 20 | 21 | System.out.println("\nAfter sorting:"); 22 | display(ducks); 23 | } 24 | 25 | public static void display(Duck[] ducks) { 26 | for (int i = 0; i < ducks.length; i++) { 27 | System.out.println(ducks[i]); 28 | } 29 | } 30 | } --------------------------------------------------------------------------------