├── README.md └── src ├── .DS_Store └── headfirst ├── .DS_Store ├── adapter ├── .DS_Store ├── ducks │ ├── .DS_Store │ ├── 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 ├── combined └── djview │ ├── BPMObserver.java │ ├── BeatBar.java │ ├── BeatController.java │ ├── BeatModel.java │ ├── BeatModelInterface.java │ ├── BeatObserver.java │ ├── ControllerInterface.java │ ├── DJTestDrive.java │ ├── DJView.java │ ├── HeartAdapter.java │ ├── HeartController.java │ ├── HeartModel.java │ ├── HeartModelInterface.java │ └── HeartTestDrive.java ├── combining ├── adapter │ ├── DecoyDuck.java │ ├── DuckCall.java │ ├── DuckSimulator.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java ├── composite │ ├── AbstractDuckFactory.java │ ├── CountingDuckFactory.java │ ├── DecoyDuck.java │ ├── DuckCall.java │ ├── DuckFactory.java │ ├── DuckSimulator.java │ ├── Flock.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── QuackCounter.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java ├── decorator │ ├── DecoyDuck.java │ ├── DuckCall.java │ ├── DuckSimulator.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── QuackCounter.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java ├── ducks │ ├── DecoyDuck.java │ ├── DuckCall.java │ ├── DuckSimulator.java │ ├── MallardDuck.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java ├── factory │ ├── AbstractDuckFactory.java │ ├── CountingDuckFactory.java │ ├── DecoyDuck.java │ ├── DuckCall.java │ ├── DuckFactory.java │ ├── DuckSimulator.java │ ├── Goose.java │ ├── GooseAdapter.java │ ├── MallardDuck.java │ ├── QuackCounter.java │ ├── Quackable.java │ ├── RedheadDuck.java │ └── RubberDuck.java └── observer │ ├── .QuackDecorator.java.swp │ ├── AbstractDuckFactory.java │ ├── CountingDuckFactory.java │ ├── DecoyDuck.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 ├── command ├── party │ ├── CeilingFan.java │ ├── CeilingFanHighCommand.java │ ├── CeilingFanMediumCommand.java │ ├── CeilingFanOffCommand.java │ ├── Command.java │ ├── Hottub.java │ ├── HottubOffCommand.java │ ├── HottubOnCommand.java │ ├── Light.java │ ├── LightOffCommand.java │ ├── LightOnCommand.java │ ├── LivingroomLightOffCommand.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 ├── decorator ├── io │ ├── InputTest.java │ └── LowerCaseInputStream.java └── starbuzz │ ├── Beverage.java │ ├── CondimentDecorator.java │ ├── DarkRoast.java │ ├── Decaf.java │ ├── Espresso.java │ ├── HouseBlend.java │ ├── Milk.java │ ├── Mocha.java │ ├── Soy.java │ ├── StarbuzzCoffee.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 │ ├── DependentPizzaStore.java │ ├── NYPizzaStore.java │ ├── NYStyleCheesePizza.java │ ├── NYStyleClamPizza.java │ ├── NYStylePepperoniPizza.java │ ├── NYStyleVeggiePizza.java │ ├── Pizza.java │ ├── PizzaStore.java │ └── PizzaTestDrive.java └── pizzas │ ├── CheesePizza.java │ ├── ClamPizza.java │ ├── PepperoniPizza.java │ ├── Pizza.java │ ├── PizzaStore.java │ ├── PizzaTestDrive.java │ ├── SimplePizzaFactory.java │ └── VeggiePizza.java ├── iterator ├── dinermerger │ ├── AlternatingDinerMenuIterator.java │ ├── ArrayIterator.java │ ├── ArrayListIterator.java │ ├── DinerMenu.java │ ├── DinerMenuIterator.java │ ├── Iterator.java │ ├── Menu.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── PancakeHouseMenu.java │ ├── PancakeHouseMenuIterator.java │ └── Waitress.java ├── dinermergercafe │ ├── AlternatingDinerMenuIterator.java │ ├── CafeMenu.java │ ├── DinerMenu.java │ ├── DinerMenuIterator.java │ ├── Menu.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── PancakeHouseMenu.java │ └── Waitress.java ├── dinermergeri │ ├── AlternatingDinerMenuIterator.java │ ├── DinerMenu.java │ ├── DinerMenuIterator.java │ ├── Menu.java │ ├── MenuItem.java │ ├── MenuTestDrive.java │ ├── PancakeHouseMenu.java │ └── Waitress.java └── transition │ ├── Menu.java │ ├── MenuItem.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 │ └── WeatherStationHeatIndex.java └── weatherobservable │ ├── CurrentConditionsDisplay.java │ ├── DisplayElement.java │ ├── ForecastDisplay.java │ ├── HeatIndexDisplay.java │ ├── StatisticsDisplay.java │ ├── WeatherData.java │ ├── WeatherStation.java │ └── WeatherStationHeatIndex.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 ├── gumballmonitor │ ├── GumballMachine.java │ ├── GumballMachineTestDrive.java │ ├── GumballMonitor.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 ├── chocolate │ ├── ChocolateBoiler.java │ └── ChocolateController.java ├── classic │ └── Singleton.java ├── dcl │ ├── Singleton.java │ └── SingletonClient.java ├── stat │ ├── 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 ├── DecoyDuck.java ├── Duck.java ├── FakeQuack.java ├── FlyBehavior.java ├── FlyNoWay.java ├── FlyRocketPowered.java ├── FlyWithWings.java ├── MallardDuck.java ├── MiniDuckSimulator.java ├── MiniDuckSimulator1.java ├── ModelDuck.java ├── MuteQuack.java ├── Quack.java ├── QuackBehavior.java ├── RedHeadDuck.java ├── RubberDuck.java └── Squeak.java └── templatemethod ├── applet ├── AppletSource.txt └── 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 | # headfirst_design_patterns 2 | 3 | http://www.javaguides.net/2018/07/factory-pattern-from-head-first-design-patterns.html 4 | 5 | http://www.javaguides.net/2018/07/decorator-pattern-from-head-first-design-patterns.html 6 | 7 | http://www.javaguides.net/2018/07/template-pattern-from-head-first-design-patterns.html 8 | 9 | http://www.javaguides.net/2018/07/observer-pattern-from-head-first-design-patterns.html 10 | 11 | http://www.javaguides.net/2018/07/facade-pattern-from-head-first-design-patterns.html 12 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/headfirst_design_patterns/94719f2611ceeac143b66e11395ea30b4beba4b0/src/.DS_Store -------------------------------------------------------------------------------- /src/headfirst/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/headfirst_design_patterns/94719f2611ceeac143b66e11395ea30b4beba4b0/src/headfirst/.DS_Store -------------------------------------------------------------------------------- /src/headfirst/adapter/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/headfirst_design_patterns/94719f2611ceeac143b66e11395ea30b4beba4b0/src/headfirst/adapter/.DS_Store -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/headfirst_design_patterns/94719f2611ceeac143b66e11395ea30b4beba4b0/src/headfirst/adapter/ducks/.DS_Store -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/Duck.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public interface Duck { 4 | public void quack(); 5 | public void fly(); 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/DuckAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | import java.util.Random; 3 | 4 | public class DuckAdapter implements Turkey { 5 | Duck duck; 6 | Random rand; 7 | 8 | public DuckAdapter(Duck duck) { 9 | this.duck = duck; 10 | rand = new Random(); 11 | } 12 | 13 | public void gobble() { 14 | duck.quack(); 15 | } 16 | 17 | public void fly() { 18 | if (rand.nextInt(5) == 0) { 19 | duck.fly(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/DuckTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public class DuckTestDrive { 4 | public static void main(String[] args) { 5 | MallardDuck duck = new MallardDuck(); 6 | 7 | WildTurkey turkey = new WildTurkey(); 8 | Duck turkeyAdapter = new TurkeyAdapter(turkey); 9 | 10 | System.out.println("The Turkey says..."); 11 | turkey.gobble(); 12 | turkey.fly(); 13 | 14 | System.out.println("\nThe Duck says..."); 15 | testDuck(duck); 16 | 17 | System.out.println("\nThe TurkeyAdapter says..."); 18 | testDuck(turkeyAdapter); 19 | } 20 | 21 | static void testDuck(Duck duck) { 22 | duck.quack(); 23 | duck.fly(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public class MallardDuck implements Duck { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | 8 | public void fly() { 9 | System.out.println("I'm flying"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/Turkey.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public interface Turkey { 4 | public void gobble(); 5 | public void fly(); 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/TurkeyAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public class TurkeyAdapter implements Duck { 4 | Turkey turkey; 5 | 6 | public TurkeyAdapter(Turkey turkey) { 7 | this.turkey = turkey; 8 | } 9 | 10 | public void quack() { 11 | turkey.gobble(); 12 | } 13 | 14 | public void fly() { 15 | for(int i=0; i < 5; i++) { 16 | turkey.fly(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/TurkeyTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public class TurkeyTestDrive { 4 | public static void main(String[] args) { 5 | MallardDuck duck = new MallardDuck(); 6 | Turkey duckAdapter = new DuckAdapter(duck); 7 | 8 | for(int i=0;i<10;i++) { 9 | System.out.println("The DuckAdapter says..."); 10 | duckAdapter.gobble(); 11 | duckAdapter.fly(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/headfirst/adapter/ducks/WildTurkey.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.ducks; 2 | 3 | public class WildTurkey implements Turkey { 4 | public void gobble() { 5 | System.out.println("Gobble gobble"); 6 | } 7 | 8 | public void fly() { 9 | System.out.println("I'm flying a short distance"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/adapter/iterenum/EI.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.iterenum; 2 | 3 | import java.util.*; 4 | 5 | public class EI { 6 | public static void main (String args[]) { 7 | Vector v = new Vector(Arrays.asList(args)); 8 | Enumeration enumeration = v.elements(); 9 | while (enumeration.hasMoreElements()) { 10 | System.out.println(enumeration.nextElement()); 11 | } 12 | Iterator iterator = v.iterator(); 13 | while (iterator.hasNext()) { 14 | System.out.println(iterator.next()); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/adapter/iterenum/EnumerationIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.iterenum; 2 | 3 | import java.util.*; 4 | 5 | public class EnumerationIterator implements Iterator { 6 | Enumeration enumeration; 7 | 8 | public EnumerationIterator(Enumeration enumeration) { 9 | this.enumeration = enumeration; 10 | } 11 | 12 | public boolean hasNext() { 13 | return enumeration.hasMoreElements(); 14 | } 15 | 16 | public Object next() { 17 | return enumeration.nextElement(); 18 | } 19 | 20 | public void remove() { 21 | throw new UnsupportedOperationException(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/adapter/iterenum/EnumerationIteratorTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.iterenum; 2 | 3 | import java.util.*; 4 | 5 | public class EnumerationIteratorTestDrive { 6 | public static void main (String args[]) { 7 | Vector v = new Vector(Arrays.asList(args)); 8 | Iterator iterator = new EnumerationIterator(v.elements()); 9 | while (iterator.hasNext()) { 10 | System.out.println(iterator.next()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/adapter/iterenum/IteratorEnumeration.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.iterenum; 2 | 3 | import java.util.*; 4 | 5 | public class IteratorEnumeration implements Enumeration { 6 | Iterator iterator; 7 | 8 | public IteratorEnumeration(Iterator iterator) { 9 | this.iterator = iterator; 10 | } 11 | 12 | public boolean hasMoreElements() { 13 | return iterator.hasNext(); 14 | } 15 | 16 | public Object nextElement() { 17 | return iterator.next(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/adapter/iterenum/IteratorEnumerationTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.adapter.iterenum; 2 | 3 | import java.util.*; 4 | 5 | public class IteratorEnumerationTestDrive { 6 | public static void main (String args[]) { 7 | ArrayList l = new ArrayList(Arrays.asList(args)); 8 | Enumeration enumeration = new IteratorEnumeration(l.iterator()); 9 | while (enumeration.hasMoreElements()) { 10 | System.out.println(enumeration.nextElement()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/BPMObserver.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public interface BPMObserver { 4 | void updateBPM(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/BeatBar.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | import java.awt.*; 4 | import java.awt.event.*; 5 | import javax.swing.*; 6 | 7 | public class BeatBar extends JProgressBar implements Runnable { 8 | JProgressBar progressBar; 9 | Thread thread; 10 | 11 | public BeatBar() { 12 | thread = new Thread(this); 13 | setMaximum(100); 14 | thread.start(); 15 | } 16 | 17 | public void run() { 18 | for(;;) { 19 | int value = getValue(); 20 | value = (int)(value * .75); 21 | setValue(value); 22 | repaint(); 23 | try { 24 | Thread.sleep(50); 25 | } catch (Exception e) {}; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/BeatController.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public class BeatController implements ControllerInterface { 4 | BeatModelInterface model; 5 | DJView view; 6 | 7 | public BeatController(BeatModelInterface model) { 8 | this.model = model; 9 | view = new DJView(this, model); 10 | view.createView(); 11 | view.createControls(); 12 | view.disableStopMenuItem(); 13 | view.enableStartMenuItem(); 14 | model.initialize(); 15 | } 16 | 17 | public void start() { 18 | model.on(); 19 | view.disableStartMenuItem(); 20 | view.enableStopMenuItem(); 21 | } 22 | 23 | public void stop() { 24 | model.off(); 25 | view.disableStopMenuItem(); 26 | view.enableStartMenuItem(); 27 | } 28 | 29 | public void increaseBPM() { 30 | int bpm = model.getBPM(); 31 | model.setBPM(bpm + 1); 32 | } 33 | 34 | public void decreaseBPM() { 35 | int bpm = model.getBPM(); 36 | model.setBPM(bpm - 1); 37 | } 38 | 39 | public void setBPM(int bpm) { 40 | model.setBPM(bpm); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/BeatModelInterface.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public interface BeatModelInterface { 4 | void initialize(); 5 | 6 | void on(); 7 | 8 | void off(); 9 | 10 | void setBPM(int bpm); 11 | 12 | int getBPM(); 13 | 14 | void registerObserver(BeatObserver o); 15 | 16 | void removeObserver(BeatObserver o); 17 | 18 | void registerObserver(BPMObserver o); 19 | 20 | void removeObserver(BPMObserver o); 21 | } 22 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/BeatObserver.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public interface BeatObserver { 4 | void updateBeat(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/ControllerInterface.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public interface ControllerInterface { 4 | void start(); 5 | void stop(); 6 | void increaseBPM(); 7 | void decreaseBPM(); 8 | void setBPM(int bpm); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/DJTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public class DJTestDrive { 4 | 5 | public static void main (String[] args) { 6 | BeatModelInterface model = new BeatModel(); 7 | ControllerInterface controller = new BeatController(model); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/HeartAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public class HeartAdapter implements BeatModelInterface { 4 | HeartModelInterface heart; 5 | 6 | public HeartAdapter(HeartModelInterface heart) { 7 | this.heart = heart; 8 | } 9 | 10 | public void initialize() {} 11 | 12 | public void on() {} 13 | 14 | public void off() {} 15 | 16 | public int getBPM() { 17 | return heart.getHeartRate(); 18 | } 19 | 20 | public void setBPM(int bpm) {} 21 | 22 | public void registerObserver(BeatObserver o) { 23 | heart.registerObserver(o); 24 | } 25 | 26 | public void removeObserver(BeatObserver o) { 27 | heart.removeObserver(o); 28 | } 29 | 30 | public void registerObserver(BPMObserver o) { 31 | heart.registerObserver(o); 32 | } 33 | 34 | public void removeObserver(BPMObserver o) { 35 | heart.removeObserver(o); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/HeartController.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public class HeartController implements ControllerInterface { 4 | HeartModelInterface model; 5 | DJView view; 6 | 7 | public HeartController(HeartModelInterface model) { 8 | this.model = model; 9 | view = new DJView(this, new HeartAdapter(model)); 10 | view.createView(); 11 | view.createControls(); 12 | view.disableStopMenuItem(); 13 | view.disableStartMenuItem(); 14 | } 15 | 16 | public void start() {} 17 | 18 | public void stop() {} 19 | 20 | public void increaseBPM() {} 21 | 22 | public void decreaseBPM() {} 23 | 24 | public void setBPM(int bpm) {} 25 | } 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/HeartModelInterface.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public interface HeartModelInterface { 4 | int getHeartRate(); 5 | void registerObserver(BeatObserver o); 6 | void removeObserver(BeatObserver o); 7 | void registerObserver(BPMObserver o); 8 | void removeObserver(BPMObserver o); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combined/djview/HeartTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.combined.djview; 2 | 3 | public class HeartTestDrive { 4 | 5 | public static void main (String[] args) { 6 | HeartModel heartModel = new HeartModel(); 7 | ControllerInterface model = new HeartController(heartModel); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class DecoyDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("<< Silence >>"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/DuckCall.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class DuckCall implements Quackable { 4 | public void quack() { 5 | System.out.println("Kwak"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class DuckSimulator { 4 | public static void main(String[] args) { 5 | DuckSimulator simulator = new DuckSimulator(); 6 | simulator.simulate(); 7 | } 8 | 9 | void simulate() { 10 | Quackable mallardDuck = new MallardDuck(); 11 | Quackable redheadDuck = new RedheadDuck(); 12 | Quackable duckCall = new DuckCall(); 13 | Quackable rubberDuck = new RubberDuck(); 14 | Quackable gooseDuck = new GooseAdapter(new Goose()); 15 | 16 | System.out.println("\nDuck Simulator: With Goose Adapter"); 17 | 18 | simulate(mallardDuck); 19 | simulate(redheadDuck); 20 | simulate(duckCall); 21 | simulate(rubberDuck); 22 | simulate(gooseDuck); 23 | } 24 | 25 | void simulate(Quackable duck) { 26 | duck.quack(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/Goose.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class Goose { 4 | public void honk() { 5 | System.out.println("Honk"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class GooseAdapter implements Quackable { 4 | Goose goose; 5 | 6 | public GooseAdapter(Goose goose) { 7 | this.goose = goose; 8 | } 9 | 10 | public void quack() { 11 | goose.honk(); 12 | } 13 | 14 | public String toString() { 15 | return "Goose pretending to be a Duck"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class MallardDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/Quackable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public interface Quackable { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class RedheadDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/adapter/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.adapter; 2 | 3 | public class RubberDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Squeak"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/AbstractDuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public abstract class AbstractDuckFactory { 4 | 5 | public abstract Quackable createMallardDuck(); 6 | public abstract Quackable createRedheadDuck(); 7 | public abstract Quackable createDuckCall(); 8 | public abstract Quackable createRubberDuck(); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/CountingDuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class CountingDuckFactory extends AbstractDuckFactory { 4 | 5 | public Quackable createMallardDuck() { 6 | return new QuackCounter(new MallardDuck()); 7 | } 8 | 9 | public Quackable createRedheadDuck() { 10 | return new QuackCounter(new RedheadDuck()); 11 | } 12 | 13 | public Quackable createDuckCall() { 14 | return new QuackCounter(new DuckCall()); 15 | } 16 | 17 | public Quackable createRubberDuck() { 18 | return new QuackCounter(new RubberDuck()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class DecoyDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("<< Silence >>"); 7 | } 8 | 9 | public String toString() { 10 | return "Decoy Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/DuckCall.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class DuckCall implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Kwak"); 7 | } 8 | 9 | public String toString() { 10 | return "Duck Call"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/DuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class DuckFactory extends AbstractDuckFactory { 4 | 5 | public Quackable createMallardDuck() { 6 | return new MallardDuck(); 7 | } 8 | 9 | public Quackable createRedheadDuck() { 10 | return new RedheadDuck(); 11 | } 12 | 13 | public Quackable createDuckCall() { 14 | return new DuckCall(); 15 | } 16 | 17 | public Quackable createRubberDuck() { 18 | return new RubberDuck(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/Flock.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | import java.util.Iterator; 4 | import java.util.ArrayList; 5 | 6 | public class Flock implements Quackable { 7 | ArrayList quackers = new ArrayList(); 8 | 9 | public void add(Quackable quacker) { 10 | quackers.add(quacker); 11 | } 12 | 13 | public void quack() { 14 | Iterator iterator = quackers.iterator(); 15 | while (iterator.hasNext()) { 16 | Quackable quacker = (Quackable)iterator.next(); 17 | quacker.quack(); 18 | } 19 | } 20 | 21 | public String toString() { 22 | return "Flock of Quackers"; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/Goose.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class Goose { 4 | public void honk() { 5 | System.out.println("Honk"); 6 | } 7 | 8 | public String toString() { 9 | return "Goose"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class GooseAdapter implements Quackable { 4 | Goose goose; 5 | 6 | public GooseAdapter(Goose goose) { 7 | this.goose = goose; 8 | } 9 | 10 | public void quack() { 11 | goose.honk(); 12 | } 13 | 14 | public String toString() { 15 | return "Goose pretending to be a Duck"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class MallardDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Quack"); 7 | } 8 | 9 | public String toString() { 10 | return "Mallard Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/QuackCounter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class QuackCounter implements Quackable { 4 | Quackable duck; 5 | static int numberOfQuacks; 6 | 7 | public QuackCounter(Quackable duck) { 8 | this.duck = duck; 9 | } 10 | 11 | public void quack() { 12 | duck.quack(); 13 | numberOfQuacks++; 14 | } 15 | 16 | public static int getQuacks() { 17 | return numberOfQuacks; 18 | } 19 | 20 | public String toString() { 21 | return duck.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/Quackable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public interface Quackable { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class RedheadDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | 8 | public String toString() { 9 | return "Redhead Duck"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/combining/composite/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.composite; 2 | 3 | public class RubberDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Squeak"); 7 | } 8 | 9 | public String toString() { 10 | return "Rubber Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class DecoyDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("<< Silence >>"); 7 | } 8 | 9 | public String toString() { 10 | return "Decoy Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/DuckCall.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class DuckCall implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Kwak"); 7 | } 8 | 9 | public String toString() { 10 | return "Duck Call"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class DuckSimulator { 4 | public static void main(String[] args) { 5 | DuckSimulator simulator = new DuckSimulator(); 6 | simulator.simulate(); 7 | } 8 | 9 | void simulate() { 10 | Quackable mallardDuck = new QuackCounter(new MallardDuck()); 11 | Quackable redheadDuck = new QuackCounter(new RedheadDuck()); 12 | Quackable duckCall = new QuackCounter(new DuckCall()); 13 | Quackable rubberDuck = new QuackCounter(new RubberDuck()); 14 | Quackable gooseDuck = new GooseAdapter(new Goose()); 15 | 16 | System.out.println("\nDuck Simulator: With Decorator"); 17 | 18 | simulate(mallardDuck); 19 | simulate(redheadDuck); 20 | simulate(duckCall); 21 | simulate(rubberDuck); 22 | simulate(gooseDuck); 23 | 24 | System.out.println("The ducks quacked " + 25 | QuackCounter.getQuacks() + " times"); 26 | } 27 | 28 | void simulate(Quackable duck) { 29 | duck.quack(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/Goose.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class Goose { 4 | public void honk() { 5 | System.out.println("Honk"); 6 | } 7 | 8 | public String toString() { 9 | return "Goose"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class GooseAdapter implements Quackable { 4 | Goose goose; 5 | 6 | public GooseAdapter(Goose goose) { 7 | this.goose = goose; 8 | } 9 | 10 | public void quack() { 11 | goose.honk(); 12 | } 13 | 14 | public String toString() { 15 | return "Goose pretending to be a Duck"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class MallardDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Quack"); 7 | } 8 | 9 | public String toString() { 10 | return "Mallard Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/QuackCounter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class QuackCounter implements Quackable { 4 | Quackable duck; 5 | static int numberOfQuacks; 6 | 7 | public QuackCounter (Quackable duck) { 8 | this.duck = duck; 9 | } 10 | 11 | public void quack() { 12 | duck.quack(); 13 | numberOfQuacks++; 14 | } 15 | 16 | public static int getQuacks() { 17 | return numberOfQuacks; 18 | } 19 | public String toString() { 20 | return duck.toString(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/Quackable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public interface Quackable { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class RedheadDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/decorator/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.decorator; 2 | 3 | public class RubberDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Squeak"); 7 | } 8 | 9 | public String toString() { 10 | return "Rubber Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public class DecoyDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("<< Silence >>"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/DuckCall.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public class DuckCall implements Quackable { 4 | public void quack() { 5 | System.out.println("Kwak"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public class DuckSimulator { 4 | public static void main(String[] args) { 5 | DuckSimulator simulator = new DuckSimulator(); 6 | simulator.simulate(); 7 | } 8 | 9 | void simulate() { 10 | Quackable mallardDuck = new MallardDuck(); 11 | Quackable redheadDuck = new RedheadDuck(); 12 | Quackable duckCall = new DuckCall(); 13 | Quackable rubberDuck = new RubberDuck(); 14 | 15 | System.out.println("\nDuck Simulator"); 16 | 17 | simulate(mallardDuck); 18 | simulate(redheadDuck); 19 | simulate(duckCall); 20 | simulate(rubberDuck); 21 | } 22 | 23 | void simulate(Quackable duck) { 24 | duck.quack(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public class MallardDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/Quackable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public interface Quackable { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public class RedheadDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/ducks/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.ducks; 2 | 3 | public class RubberDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Squeak"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/AbstractDuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public abstract class AbstractDuckFactory { 4 | 5 | public abstract Quackable createMallardDuck(); 6 | public abstract Quackable createRedheadDuck(); 7 | public abstract Quackable createDuckCall(); 8 | public abstract Quackable createRubberDuck(); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/CountingDuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class CountingDuckFactory extends AbstractDuckFactory { 4 | 5 | public Quackable createMallardDuck() { 6 | return new QuackCounter(new MallardDuck()); 7 | } 8 | 9 | public Quackable createRedheadDuck() { 10 | return new QuackCounter(new RedheadDuck()); 11 | } 12 | 13 | public Quackable createDuckCall() { 14 | return new QuackCounter(new DuckCall()); 15 | } 16 | 17 | public Quackable createRubberDuck() { 18 | return new QuackCounter(new RubberDuck()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class DecoyDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("<< Silence >>"); 7 | } 8 | 9 | public String toString() { 10 | return "Decoy Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/DuckCall.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class DuckCall implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Kwak"); 7 | } 8 | 9 | public String toString() { 10 | return "Duck Call"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/DuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class DuckFactory extends AbstractDuckFactory { 4 | 5 | public Quackable createMallardDuck() { 6 | return new MallardDuck(); 7 | } 8 | 9 | public Quackable createRedheadDuck() { 10 | return new RedheadDuck(); 11 | } 12 | 13 | public Quackable createDuckCall() { 14 | return new DuckCall(); 15 | } 16 | 17 | public Quackable createRubberDuck() { 18 | return new RubberDuck(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/DuckSimulator.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class DuckSimulator { 4 | public static void main(String[] args) { 5 | DuckSimulator simulator = new DuckSimulator(); 6 | AbstractDuckFactory duckFactory = new CountingDuckFactory(); 7 | 8 | simulator.simulate(duckFactory); 9 | } 10 | 11 | void simulate(AbstractDuckFactory duckFactory) { 12 | Quackable mallardDuck = duckFactory.createMallardDuck(); 13 | Quackable redheadDuck = duckFactory.createRedheadDuck(); 14 | Quackable duckCall = duckFactory.createDuckCall(); 15 | Quackable rubberDuck = duckFactory.createRubberDuck(); 16 | Quackable gooseDuck = new GooseAdapter(new Goose()); 17 | 18 | System.out.println("\nDuck Simulator: With Abstract Factory"); 19 | 20 | simulate(mallardDuck); 21 | simulate(redheadDuck); 22 | simulate(duckCall); 23 | simulate(rubberDuck); 24 | simulate(gooseDuck); 25 | 26 | System.out.println("The ducks quacked " + 27 | QuackCounter.getQuacks() + 28 | " times"); 29 | } 30 | 31 | void simulate(Quackable duck) { 32 | duck.quack(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/Goose.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class Goose { 4 | public void honk() { 5 | System.out.println("Honk"); 6 | } 7 | 8 | public String toString() { 9 | return "Goose"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class GooseAdapter implements Quackable { 4 | Goose goose; 5 | 6 | public GooseAdapter(Goose goose) { 7 | this.goose = goose; 8 | } 9 | 10 | public void quack() { 11 | goose.honk(); 12 | } 13 | 14 | public String toString() { 15 | return "Goose pretending to be a Duck"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class MallardDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Quack"); 7 | } 8 | 9 | public String toString() { 10 | return "Mallard Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/QuackCounter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class QuackCounter implements Quackable { 4 | Quackable duck; 5 | static int numberOfQuacks; 6 | 7 | public QuackCounter(Quackable duck) { 8 | this.duck = duck; 9 | } 10 | 11 | public void quack() { 12 | duck.quack(); 13 | numberOfQuacks++; 14 | } 15 | 16 | public static int getQuacks() { 17 | return numberOfQuacks; 18 | } 19 | 20 | public String toString() { 21 | return duck.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/Quackable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public interface Quackable { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class RedheadDuck implements Quackable { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/combining/factory/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.factory; 2 | 3 | public class RubberDuck implements Quackable { 4 | 5 | public void quack() { 6 | System.out.println("Squeak"); 7 | } 8 | 9 | public String toString() { 10 | return "Rubber Duck"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/.QuackDecorator.java.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RameshMF/headfirst_design_patterns/94719f2611ceeac143b66e11395ea30b4beba4b0/src/headfirst/combining/observer/.QuackDecorator.java.swp -------------------------------------------------------------------------------- /src/headfirst/combining/observer/AbstractDuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public abstract class AbstractDuckFactory { 4 | 5 | public abstract Quackable createMallardDuck(); 6 | public abstract Quackable createRedheadDuck(); 7 | public abstract Quackable createDuckCall(); 8 | public abstract Quackable createRubberDuck(); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/CountingDuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class CountingDuckFactory extends AbstractDuckFactory { 4 | 5 | public Quackable createMallardDuck() { 6 | return new QuackCounter(new MallardDuck()); 7 | } 8 | 9 | public Quackable createRedheadDuck() { 10 | return new QuackCounter(new RedheadDuck()); 11 | } 12 | 13 | public Quackable createDuckCall() { 14 | return new QuackCounter(new DuckCall()); 15 | } 16 | 17 | public Quackable createRubberDuck() { 18 | return new QuackCounter(new RubberDuck()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class DecoyDuck implements Quackable { 4 | Observable observable; 5 | 6 | public DecoyDuck() { 7 | observable = new Observable(this); 8 | } 9 | 10 | public void quack() { 11 | System.out.println("<< Silence >>"); 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 | 23 | public String toString() { 24 | return "Decoy Duck"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/DuckCall.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class DuckCall implements Quackable { 4 | Observable observable; 5 | 6 | public DuckCall() { 7 | observable = new Observable(this); 8 | } 9 | 10 | public void quack() { 11 | System.out.println("Kwak"); 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 | 23 | public String toString() { 24 | return "Duck Call"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/DuckFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class DuckFactory extends AbstractDuckFactory { 4 | 5 | public Quackable createMallardDuck() { 6 | return new MallardDuck(); 7 | } 8 | 9 | public Quackable createRedheadDuck() { 10 | return new RedheadDuck(); 11 | } 12 | 13 | public Quackable createDuckCall() { 14 | return new DuckCall(); 15 | } 16 | 17 | public Quackable createRubberDuck() { 18 | return new RubberDuck(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/Flock.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | import java.util.Iterator; 4 | import java.util.ArrayList; 5 | 6 | public class Flock implements Quackable { 7 | ArrayList ducks = new ArrayList(); 8 | 9 | public void add(Quackable duck) { 10 | ducks.add(duck); 11 | } 12 | 13 | public void quack() { 14 | Iterator iterator = ducks.iterator(); 15 | while (iterator.hasNext()) { 16 | Quackable duck = (Quackable)iterator.next(); 17 | duck.quack(); 18 | } 19 | } 20 | 21 | public void registerObserver(Observer observer) { 22 | Iterator iterator = ducks.iterator(); 23 | while (iterator.hasNext()) { 24 | Quackable duck = (Quackable)iterator.next(); 25 | duck.registerObserver(observer); 26 | } 27 | } 28 | 29 | public void notifyObservers() { } 30 | 31 | public String toString() { 32 | return "Flock of Ducks"; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/Goose.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class Goose { 4 | 5 | public void honk() { 6 | System.out.println("Honk"); 7 | } 8 | 9 | public String toString() { 10 | return "Goose"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/GooseAdapter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class GooseAdapter implements Quackable { 4 | Goose goose; 5 | Observable observable; 6 | 7 | public GooseAdapter(Goose goose) { 8 | this.goose = goose; 9 | observable = new Observable(this); 10 | } 11 | 12 | public void quack() { 13 | goose.honk(); 14 | notifyObservers(); 15 | } 16 | 17 | public void registerObserver(Observer observer) { 18 | observable.registerObserver(observer); 19 | } 20 | 21 | public void notifyObservers() { 22 | observable.notifyObservers(); 23 | } 24 | 25 | public String toString() { 26 | return "Goose pretending to be a Duck"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class MallardDuck implements Quackable { 4 | Observable observable; 5 | 6 | public MallardDuck() { 7 | observable = new Observable(this); 8 | } 9 | 10 | public void quack() { 11 | System.out.println("Quack"); 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 | 23 | public String toString() { 24 | return "Mallard Duck"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/Observable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | import java.util.Iterator; 4 | import java.util.ArrayList; 5 | 6 | public class Observable implements QuackObservable { 7 | ArrayList observers = new ArrayList(); 8 | QuackObservable duck; 9 | 10 | public Observable(QuackObservable duck) { 11 | this.duck = duck; 12 | } 13 | 14 | public void registerObserver(Observer observer) { 15 | observers.add(observer); 16 | } 17 | 18 | public void notifyObservers() { 19 | Iterator iterator = observers.iterator(); 20 | while (iterator.hasNext()) { 21 | Observer observer = (Observer)iterator.next(); 22 | observer.update(duck); 23 | } 24 | } 25 | 26 | public Iterator getObservers() { 27 | return observers.iterator(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/Observer.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public interface Observer { 4 | public void update(QuackObservable duck); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/QuackCounter.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class QuackCounter implements Quackable { 4 | Quackable duck; 5 | static int numberOfQuacks; 6 | 7 | public QuackCounter(Quackable duck) { 8 | this.duck = duck; 9 | } 10 | 11 | public void quack() { 12 | duck.quack(); 13 | numberOfQuacks++; 14 | } 15 | 16 | public static int getQuacks() { 17 | return numberOfQuacks; 18 | } 19 | 20 | public void registerObserver(Observer observer) { 21 | duck.registerObserver(observer); 22 | } 23 | 24 | public void notifyObservers() { 25 | duck.notifyObservers(); 26 | } 27 | 28 | public String toString() { 29 | return duck.toString(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/QuackObservable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public interface QuackObservable { 4 | public void registerObserver(Observer observer); 5 | public void notifyObservers(); 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/Quackable.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public interface Quackable extends QuackObservable { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/Quackologist.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class Quackologist implements Observer { 4 | 5 | public void update(QuackObservable duck) { 6 | System.out.println("Quackologist: " + duck + " just quacked."); 7 | } 8 | 9 | public String toString() { 10 | return "Quackologist"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/RedheadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class RedheadDuck implements Quackable { 4 | Observable observable; 5 | 6 | public RedheadDuck() { 7 | observable = new Observable(this); 8 | } 9 | 10 | public void quack() { 11 | System.out.println("Quack"); 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 | 23 | public String toString() { 24 | return "Redhead Duck"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/combining/observer/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.combining.observer; 2 | 3 | public class RubberDuck implements Quackable { 4 | Observable observable; 5 | 6 | public RubberDuck() { 7 | observable = new Observable(this); 8 | } 9 | 10 | public void quack() { 11 | System.out.println("Squeak"); 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 | 23 | public String toString() { 24 | return "Rubber Duck"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/command/party/CeilingFan.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class CeilingFan { 4 | public static final int HIGH = 3; 5 | public static final int MEDIUM = 2; 6 | public static final int LOW = 1; 7 | public static final int OFF = 0; 8 | String location; 9 | int speed; 10 | 11 | public CeilingFan(String location) { 12 | this.location = location; 13 | } 14 | 15 | public void high() { 16 | // turns the ceiling fan on to high 17 | speed = HIGH; 18 | System.out.println(location + " ceiling fan is on high"); 19 | } 20 | 21 | public void medium() { 22 | // turns the ceiling fan on to medium 23 | speed = MEDIUM; 24 | System.out.println(location + " ceiling fan is on medium"); 25 | } 26 | 27 | public void low() { 28 | // turns the ceiling fan on to low 29 | speed = LOW; 30 | System.out.println(location + " ceiling fan is on low"); 31 | } 32 | 33 | public void off() { 34 | // turns the ceiling fan off 35 | speed = OFF; 36 | System.out.println(location + " ceiling fan is off"); 37 | } 38 | 39 | public int getSpeed() { 40 | return speed; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/headfirst/command/party/CeilingFanHighCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class CeilingFanHighCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanHighCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | public void execute() { 11 | prevSpeed = ceilingFan.getSpeed(); 12 | ceilingFan.high(); 13 | } 14 | public void undo() { 15 | switch (prevSpeed) { 16 | case CeilingFan.HIGH: ceilingFan.high(); break; 17 | case CeilingFan.MEDIUM: ceilingFan.medium(); break; 18 | case CeilingFan.LOW: ceilingFan.low(); break; 19 | default: ceilingFan.off(); break; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/command/party/CeilingFanMediumCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class CeilingFanMediumCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanMediumCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | public void execute() { 11 | prevSpeed = ceilingFan.getSpeed(); 12 | ceilingFan.medium(); 13 | } 14 | public void undo() { 15 | switch (prevSpeed) { 16 | case CeilingFan.HIGH: ceilingFan.high(); break; 17 | case CeilingFan.MEDIUM: ceilingFan.medium(); break; 18 | case CeilingFan.LOW: ceilingFan.low(); break; 19 | default: ceilingFan.off(); break; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/command/party/CeilingFanOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class CeilingFanOffCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanOffCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | public void execute() { 11 | prevSpeed = ceilingFan.getSpeed(); 12 | ceilingFan.off(); 13 | } 14 | public void undo() { 15 | switch (prevSpeed) { 16 | case CeilingFan.HIGH: ceilingFan.high(); break; 17 | case CeilingFan.MEDIUM: ceilingFan.medium(); break; 18 | case CeilingFan.LOW: ceilingFan.low(); break; 19 | default: ceilingFan.off(); break; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/command/party/Command.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public interface Command { 4 | public void execute(); 5 | public void undo(); 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/command/party/Hottub.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class Hottub { 4 | boolean on; 5 | int temperature; 6 | 7 | public Hottub() { 8 | } 9 | 10 | public void on() { 11 | on = true; 12 | } 13 | 14 | public void off() { 15 | on = false; 16 | } 17 | 18 | public void circulate() { 19 | if (on) { 20 | System.out.println("Hottub is bubbling!"); 21 | } 22 | } 23 | 24 | public void jetsOn() { 25 | if (on) { 26 | System.out.println("Hottub jets are on"); 27 | } 28 | } 29 | 30 | public void jetsOff() { 31 | if (on) { 32 | System.out.println("Hottub jets are off"); 33 | } 34 | } 35 | 36 | public void setTemperature(int temperature) { 37 | if (temperature > this.temperature) { 38 | System.out.println("Hottub is heating to a steaming " + temperature + " degrees"); 39 | } 40 | else { 41 | System.out.println("Hottub is cooling to " + temperature + " degrees"); 42 | } 43 | this.temperature = temperature; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/headfirst/command/party/HottubOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class HottubOffCommand implements Command { 4 | Hottub hottub; 5 | 6 | public HottubOffCommand(Hottub hottub) { 7 | this.hottub = hottub; 8 | } 9 | 10 | public void execute() { 11 | hottub.setTemperature(98); 12 | hottub.off(); 13 | } 14 | public void undo() { 15 | hottub.on(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/HottubOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class HottubOnCommand implements Command { 4 | Hottub hottub; 5 | 6 | public HottubOnCommand(Hottub hottub) { 7 | this.hottub = hottub; 8 | } 9 | public void execute() { 10 | hottub.on(); 11 | hottub.setTemperature(104); 12 | hottub.circulate(); 13 | } 14 | public void undo() { 15 | hottub.off(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/Light.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class Light { 4 | String location; 5 | int level; 6 | 7 | public Light(String location) { 8 | this.location = location; 9 | } 10 | 11 | public void on() { 12 | level = 100; 13 | System.out.println("Light is on"); 14 | } 15 | 16 | public void off() { 17 | level = 0; 18 | System.out.println("Light is off"); 19 | } 20 | 21 | public void dim(int level) { 22 | this.level = level; 23 | if (level == 0) { 24 | off(); 25 | } 26 | else { 27 | System.out.println("Light is dimmed to " + level + "%"); 28 | } 29 | } 30 | 31 | public int getLevel() { 32 | return level; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/headfirst/command/party/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class LightOffCommand implements Command { 4 | Light light; 5 | 6 | public LightOffCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.off(); 12 | } 13 | 14 | public void undo() { 15 | light.on(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class LightOnCommand implements Command { 4 | Light light; 5 | 6 | public LightOnCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.on(); 12 | } 13 | 14 | public void undo() { 15 | light.off(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/LivingroomLightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class LivingroomLightOffCommand implements Command { 4 | Light light; 5 | 6 | public LivingroomLightOffCommand(Light light) { 7 | this.light = light; 8 | } 9 | public void execute() { 10 | light.off(); 11 | } 12 | public void undo() { 13 | light.on(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/command/party/LivingroomLightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class LivingroomLightOnCommand implements Command { 4 | Light light; 5 | 6 | public LivingroomLightOnCommand(Light light) { 7 | this.light = light; 8 | } 9 | public void execute() { 10 | light.on(); 11 | } 12 | public void undo() { 13 | light.off(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/command/party/MacroCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class MacroCommand implements Command { 4 | Command[] commands; 5 | 6 | public MacroCommand(Command[] commands) { 7 | this.commands = commands; 8 | } 9 | 10 | public void execute() { 11 | for (int i = 0; i < commands.length; i++) { 12 | commands[i].execute(); 13 | } 14 | } 15 | 16 | /** 17 | * NOTE: these commands have to be done backwards to ensure proper undo functionality 18 | */ 19 | public void undo() { 20 | for (int i = commands.length -1; i >= 0; i--) { 21 | commands[i].undo(); 22 | } 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /src/headfirst/command/party/NoCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class NoCommand implements Command { 4 | public void execute() { } 5 | public void undo() { } 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/command/party/Stereo.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class Stereo { 4 | String location; 5 | 6 | public Stereo(String location) { 7 | this.location = location; 8 | } 9 | 10 | public void on() { 11 | System.out.println(location + " stereo is on"); 12 | } 13 | 14 | public void off() { 15 | System.out.println(location + " stereo is off"); 16 | } 17 | 18 | public void setCD() { 19 | System.out.println(location + " stereo is set for CD input"); 20 | } 21 | 22 | public void setDVD() { 23 | System.out.println(location + " stereo is set for DVD input"); 24 | } 25 | 26 | public void setRadio() { 27 | System.out.println(location + " stereo is set for Radio"); 28 | } 29 | 30 | public void setVolume(int volume) { 31 | // code to set the volume 32 | // valid range: 1-11 (after all 11 is better than 10, right?) 33 | System.out.println(location + " Stereo volume set to " + volume); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/command/party/StereoOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class StereoOffCommand implements Command { 4 | Stereo stereo; 5 | 6 | public StereoOffCommand(Stereo stereo) { 7 | this.stereo = stereo; 8 | } 9 | 10 | public void execute() { 11 | stereo.off(); 12 | } 13 | 14 | public void undo() { 15 | stereo.on(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/StereoOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class StereoOnCommand implements Command { 4 | Stereo stereo; 5 | 6 | public StereoOnCommand(Stereo stereo) { 7 | this.stereo = stereo; 8 | } 9 | 10 | public void execute() { 11 | stereo.on(); 12 | } 13 | 14 | public void undo() { 15 | stereo.off(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/StereoOnWithCDCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class StereoOnWithCDCommand implements Command { 4 | Stereo stereo; 5 | 6 | public StereoOnWithCDCommand(Stereo stereo) { 7 | this.stereo = stereo; 8 | } 9 | 10 | public void execute() { 11 | stereo.on(); 12 | stereo.setCD(); 13 | stereo.setVolume(11); 14 | } 15 | 16 | public void undo() { 17 | stereo.off(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/command/party/TV.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class TV { 4 | String location; 5 | int channel; 6 | 7 | public TV(String location) { 8 | this.location = location; 9 | } 10 | 11 | public void on() { 12 | System.out.println(location + " TV is on"); 13 | } 14 | 15 | public void off() { 16 | System.out.println(location + " TV is off"); 17 | } 18 | 19 | public void setInputChannel() { 20 | this.channel = 3; 21 | System.out.println(location + " TV channel is set for DVD"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/command/party/TVOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class TVOffCommand implements Command { 4 | TV tv; 5 | 6 | public TVOffCommand(TV tv) { 7 | this.tv= tv; 8 | } 9 | 10 | public void execute() { 11 | tv.off(); 12 | } 13 | 14 | public void undo() { 15 | tv.on(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/party/TVOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.party; 2 | 3 | public class TVOnCommand implements Command { 4 | TV tv; 5 | 6 | public TVOnCommand(TV tv) { 7 | this.tv= tv; 8 | } 9 | 10 | public void execute() { 11 | tv.on(); 12 | tv.setInputChannel(); 13 | } 14 | 15 | public void undo() { 16 | tv.off(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/CeilingFan.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class CeilingFan { 4 | String location = ""; 5 | int level; 6 | public static final int HIGH = 2; 7 | public static final int MEDIUM = 1; 8 | public static final int LOW = 0; 9 | 10 | public CeilingFan(String location) { 11 | this.location = location; 12 | } 13 | 14 | public void high() { 15 | // turns the ceiling fan on to high 16 | level = HIGH; 17 | System.out.println(location + " ceiling fan is on high"); 18 | 19 | } 20 | 21 | public void medium() { 22 | // turns the ceiling fan on to medium 23 | level = MEDIUM; 24 | System.out.println(location + " ceiling fan is on medium"); 25 | } 26 | 27 | public void low() { 28 | // turns the ceiling fan on to low 29 | level = LOW; 30 | System.out.println(location + " ceiling fan is on low"); 31 | } 32 | 33 | public void off() { 34 | // turns the ceiling fan off 35 | level = 0; 36 | System.out.println(location + " ceiling fan is off"); 37 | } 38 | 39 | public int getSpeed() { 40 | return level; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/CeilingFanOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class CeilingFanOffCommand implements Command { 4 | CeilingFan ceilingFan; 5 | 6 | public CeilingFanOffCommand(CeilingFan ceilingFan) { 7 | this.ceilingFan = ceilingFan; 8 | } 9 | public void execute() { 10 | ceilingFan.off(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/CeilingFanOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class CeilingFanOnCommand implements Command { 4 | CeilingFan ceilingFan; 5 | 6 | public CeilingFanOnCommand(CeilingFan ceilingFan) { 7 | this.ceilingFan = ceilingFan; 8 | } 9 | public void execute() { 10 | ceilingFan.high(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/Command.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public interface Command { 4 | public void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/GarageDoor.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class GarageDoor { 4 | String location; 5 | 6 | public GarageDoor(String location) { 7 | this.location = location; 8 | } 9 | 10 | public void up() { 11 | System.out.println(location + " garage Door is Up"); 12 | } 13 | 14 | public void down() { 15 | System.out.println(location + " garage Door is Down"); 16 | } 17 | 18 | public void stop() { 19 | System.out.println(location + " garage Door is Stopped"); 20 | } 21 | 22 | public void lightOn() { 23 | System.out.println(location + " garage light is on"); 24 | } 25 | 26 | public void lightOff() { 27 | System.out.println(location + " garage light is off"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/GarageDoorDownCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class GarageDoorDownCommand implements Command { 4 | GarageDoor garageDoor; 5 | 6 | public GarageDoorDownCommand(GarageDoor garageDoor) { 7 | this.garageDoor = garageDoor; 8 | } 9 | 10 | public void execute() { 11 | garageDoor.up(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/GarageDoorUpCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class GarageDoorUpCommand implements Command { 4 | GarageDoor garageDoor; 5 | 6 | public GarageDoorUpCommand(GarageDoor garageDoor) { 7 | this.garageDoor = garageDoor; 8 | } 9 | 10 | public void execute() { 11 | garageDoor.up(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/Hottub.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class Hottub { 4 | boolean on; 5 | int temperature; 6 | 7 | public Hottub() { 8 | } 9 | 10 | public void on() { 11 | on = true; 12 | } 13 | 14 | public void off() { 15 | on = false; 16 | } 17 | 18 | public void bubblesOn() { 19 | if (on) { 20 | System.out.println("Hottub is bubbling!"); 21 | } 22 | } 23 | 24 | public void bubblesOff() { 25 | if (on) { 26 | System.out.println("Hottub is not bubbling"); 27 | } 28 | } 29 | 30 | public void jetsOn() { 31 | if (on) { 32 | System.out.println("Hottub jets are on"); 33 | } 34 | } 35 | 36 | public void jetsOff() { 37 | if (on) { 38 | System.out.println("Hottub jets are off"); 39 | } 40 | } 41 | 42 | public void setTemperature(int temperature) { 43 | this.temperature = temperature; 44 | } 45 | 46 | public void heat() { 47 | temperature = 105; 48 | System.out.println("Hottub is heating to a steaming 105 degrees"); 49 | } 50 | 51 | public void cool() { 52 | temperature = 98; 53 | System.out.println("Hottub is cooling to 98 degrees"); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/HottubOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class HottubOffCommand implements Command { 4 | Hottub hottub; 5 | 6 | public HottubOffCommand(Hottub hottub) { 7 | this.hottub = hottub; 8 | } 9 | 10 | public void execute() { 11 | hottub.cool(); 12 | hottub.off(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/HottubOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class HottubOnCommand implements Command { 4 | Hottub hottub; 5 | 6 | public HottubOnCommand(Hottub hottub) { 7 | this.hottub = hottub; 8 | } 9 | 10 | public void execute() { 11 | hottub.on(); 12 | hottub.heat(); 13 | hottub.bubblesOn(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/Light.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class Light { 4 | String location = ""; 5 | 6 | public Light(String location) { 7 | this.location = location; 8 | } 9 | 10 | public void on() { 11 | System.out.println(location + " light is on"); 12 | } 13 | 14 | public void off() { 15 | System.out.println(location + " light is off"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class LightOffCommand implements Command { 4 | Light light; 5 | 6 | public LightOffCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.off(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class LightOnCommand implements Command { 4 | Light light; 5 | 6 | public LightOnCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.on(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/LivingroomLightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class LivingroomLightOffCommand implements Command { 4 | Light light; 5 | 6 | public LivingroomLightOffCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.off(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/LivingroomLightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class LivingroomLightOnCommand implements Command { 4 | Light light; 5 | 6 | public LivingroomLightOnCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.on(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/NoCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class NoCommand implements Command { 4 | public void execute() { } 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/Stereo.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class Stereo { 4 | String location; 5 | 6 | public Stereo(String location) { 7 | this.location = location; 8 | } 9 | 10 | public void on() { 11 | System.out.println(location + " stereo is on"); 12 | } 13 | 14 | public void off() { 15 | System.out.println(location + " stereo is off"); 16 | } 17 | 18 | public void setCD() { 19 | System.out.println(location + " stereo is set for CD input"); 20 | } 21 | 22 | public void setDVD() { 23 | System.out.println(location + " stereo is set for DVD input"); 24 | } 25 | 26 | public void setRadio() { 27 | System.out.println(location + " stereo is set for Radio"); 28 | } 29 | 30 | public void setVolume(int volume) { 31 | // code to set the volume 32 | // valid range: 1-11 (after all 11 is better than 10, right?) 33 | System.out.println(location + " Stereo volume set to " + volume); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/StereoOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class StereoOffCommand implements Command { 4 | Stereo stereo; 5 | 6 | public StereoOffCommand(Stereo stereo) { 7 | this.stereo = stereo; 8 | } 9 | 10 | public void execute() { 11 | stereo.off(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/StereoOnWithCDCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class StereoOnWithCDCommand implements Command { 4 | Stereo stereo; 5 | 6 | public StereoOnWithCDCommand(Stereo stereo) { 7 | this.stereo = stereo; 8 | } 9 | 10 | public void execute() { 11 | stereo.on(); 12 | stereo.setCD(); 13 | stereo.setVolume(11); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/command/remote/TV.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.remote; 2 | 3 | public class TV { 4 | String location; 5 | int channel; 6 | 7 | public TV(String location) { 8 | this.location = location; 9 | } 10 | 11 | public void on() { 12 | System.out.println("TV is on"); 13 | } 14 | 15 | public void off() { 16 | System.out.println("TV is off"); 17 | } 18 | 19 | public void setInputChannel() { 20 | this.channel = 3; 21 | System.out.println("Channel is set for VCR"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/Command.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public interface Command { 4 | public void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/GarageDoor.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public class GarageDoor { 4 | 5 | public GarageDoor() { 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 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/GarageDoorOpenCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public class GarageDoorOpenCommand implements Command { 4 | GarageDoor garageDoor; 5 | 6 | public GarageDoorOpenCommand(GarageDoor garageDoor) { 7 | this.garageDoor = garageDoor; 8 | } 9 | 10 | public void execute() { 11 | garageDoor.up(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/Light.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public class Light { 4 | 5 | public Light() { 6 | } 7 | 8 | public void on() { 9 | System.out.println("Light is on"); 10 | } 11 | 12 | public void off() { 13 | System.out.println("Light is off"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public class LightOffCommand implements Command { 4 | Light light; 5 | 6 | public LightOffCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.off(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public class LightOnCommand implements Command { 4 | Light light; 5 | 6 | public LightOnCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | light.on(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/RemoteControlTest.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | public class RemoteControlTest { 4 | public static void main(String[] args) { 5 | SimpleRemoteControl remote = new SimpleRemoteControl(); 6 | Light light = new Light(); 7 | GarageDoor garageDoor = new GarageDoor(); 8 | LightOnCommand lightOn = new LightOnCommand(light); 9 | GarageDoorOpenCommand garageOpen = 10 | new GarageDoorOpenCommand(garageDoor); 11 | 12 | remote.setCommand(lightOn); 13 | remote.buttonWasPressed(); 14 | remote.setCommand(garageOpen); 15 | remote.buttonWasPressed(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/command/simpleremote/SimpleRemoteControl.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.simpleremote; 2 | 3 | import java.util.*; 4 | 5 | // 6 | // This is the invoker 7 | // 8 | public class SimpleRemoteControl { 9 | Command slot; 10 | 11 | public SimpleRemoteControl() {} 12 | 13 | public void setCommand(Command command) { 14 | slot = command; 15 | } 16 | 17 | public void buttonWasPressed() { 18 | slot.execute(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/CeilingFan.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class CeilingFan { 4 | public static final int HIGH = 3; 5 | public static final int MEDIUM = 2; 6 | public static final int LOW = 1; 7 | public static final int OFF = 0; 8 | String location; 9 | int speed; 10 | 11 | public CeilingFan(String location) { 12 | this.location = location; 13 | speed = OFF; 14 | } 15 | 16 | public void high() { 17 | speed = HIGH; 18 | System.out.println(location + " ceiling fan is on high"); 19 | } 20 | 21 | public void medium() { 22 | speed = MEDIUM; 23 | System.out.println(location + " ceiling fan is on medium"); 24 | } 25 | 26 | public void low() { 27 | speed = LOW; 28 | System.out.println(location + " ceiling fan is on low"); 29 | } 30 | 31 | public void off() { 32 | speed = OFF; 33 | System.out.println(location + " ceiling fan is off"); 34 | } 35 | 36 | public int getSpeed() { 37 | return speed; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/CeilingFanHighCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class CeilingFanHighCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanHighCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | 11 | public void execute() { 12 | prevSpeed = ceilingFan.getSpeed(); 13 | ceilingFan.high(); 14 | } 15 | 16 | public void undo() { 17 | if (prevSpeed == CeilingFan.HIGH) { 18 | ceilingFan.high(); 19 | } else if (prevSpeed == CeilingFan.MEDIUM) { 20 | ceilingFan.medium(); 21 | } else if (prevSpeed == CeilingFan.LOW) { 22 | ceilingFan.low(); 23 | } else if (prevSpeed == CeilingFan.OFF) { 24 | ceilingFan.off(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/CeilingFanLowCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class CeilingFanLowCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanLowCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | 11 | public void execute() { 12 | prevSpeed = ceilingFan.getSpeed(); 13 | ceilingFan.low(); 14 | } 15 | 16 | public void undo() { 17 | if (prevSpeed == CeilingFan.HIGH) { 18 | ceilingFan.high(); 19 | } else if (prevSpeed == CeilingFan.MEDIUM) { 20 | ceilingFan.medium(); 21 | } else if (prevSpeed == CeilingFan.LOW) { 22 | ceilingFan.low(); 23 | } else if (prevSpeed == CeilingFan.OFF) { 24 | ceilingFan.off(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/CeilingFanMediumCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class CeilingFanMediumCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanMediumCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | 11 | public void execute() { 12 | prevSpeed = ceilingFan.getSpeed(); 13 | ceilingFan.medium(); 14 | } 15 | 16 | public void undo() { 17 | if (prevSpeed == CeilingFan.HIGH) { 18 | ceilingFan.high(); 19 | } else if (prevSpeed == CeilingFan.MEDIUM) { 20 | ceilingFan.medium(); 21 | } else if (prevSpeed == CeilingFan.LOW) { 22 | ceilingFan.low(); 23 | } else if (prevSpeed == CeilingFan.OFF) { 24 | ceilingFan.off(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/CeilingFanOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class CeilingFanOffCommand implements Command { 4 | CeilingFan ceilingFan; 5 | int prevSpeed; 6 | 7 | public CeilingFanOffCommand(CeilingFan ceilingFan) { 8 | this.ceilingFan = ceilingFan; 9 | } 10 | 11 | public void execute() { 12 | prevSpeed = ceilingFan.getSpeed(); 13 | ceilingFan.off(); 14 | } 15 | 16 | public void undo() { 17 | if (prevSpeed == CeilingFan.HIGH) { 18 | ceilingFan.high(); 19 | } else if (prevSpeed == CeilingFan.MEDIUM) { 20 | ceilingFan.medium(); 21 | } else if (prevSpeed == CeilingFan.LOW) { 22 | ceilingFan.low(); 23 | } else if (prevSpeed == CeilingFan.OFF) { 24 | ceilingFan.off(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/Command.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public interface Command { 4 | public void execute(); 5 | public void undo(); 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/DimmerLightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class DimmerLightOffCommand implements Command { 4 | Light light; 5 | int prevLevel; 6 | 7 | public DimmerLightOffCommand(Light light) { 8 | this.light = light; 9 | prevLevel = 100; 10 | } 11 | 12 | public void execute() { 13 | prevLevel = light.getLevel(); 14 | light.off(); 15 | } 16 | 17 | public void undo() { 18 | light.dim(prevLevel); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/DimmerLightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class DimmerLightOnCommand implements Command { 4 | Light light; 5 | int prevLevel; 6 | 7 | public DimmerLightOnCommand(Light light) { 8 | this.light = light; 9 | } 10 | 11 | public void execute() { 12 | prevLevel = light.getLevel(); 13 | light.dim(75); 14 | } 15 | 16 | public void undo() { 17 | light.dim(prevLevel); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/Light.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class Light { 4 | String location; 5 | int level; 6 | 7 | public Light(String location) { 8 | this.location = location; 9 | } 10 | 11 | public void on() { 12 | level = 100; 13 | System.out.println("Light is on"); 14 | } 15 | 16 | public void off() { 17 | level = 0; 18 | System.out.println("Light is off"); 19 | } 20 | 21 | public void dim(int level) { 22 | this.level = level; 23 | if (level == 0) { 24 | off(); 25 | } 26 | else { 27 | System.out.println("Light is dimmed to " + level + "%"); 28 | } 29 | } 30 | 31 | public int getLevel() { 32 | return level; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/LightOffCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class LightOffCommand implements Command { 4 | Light light; 5 | int level; 6 | public LightOffCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | level = light.getLevel(); 12 | light.off(); 13 | } 14 | 15 | public void undo() { 16 | light.dim(level); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/LightOnCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class LightOnCommand implements Command { 4 | Light light; 5 | int level; 6 | public LightOnCommand(Light light) { 7 | this.light = light; 8 | } 9 | 10 | public void execute() { 11 | level = light.getLevel(); 12 | light.on(); 13 | } 14 | 15 | public void undo() { 16 | light.dim(level); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/command/undo/NoCommand.java: -------------------------------------------------------------------------------- 1 | package headfirst.command.undo; 2 | 3 | public class NoCommand implements Command { 4 | public void execute() { } 5 | public void undo() { } 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/composite/menu/MenuComponent.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menu; 2 | 3 | import java.util.*; 4 | 5 | public abstract class MenuComponent { 6 | 7 | public void add(MenuComponent menuComponent) { 8 | throw new UnsupportedOperationException(); 9 | } 10 | public void remove(MenuComponent menuComponent) { 11 | throw new UnsupportedOperationException(); 12 | } 13 | public MenuComponent getChild(int i) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | public String getName() { 18 | throw new UnsupportedOperationException(); 19 | } 20 | public String getDescription() { 21 | throw new UnsupportedOperationException(); 22 | } 23 | public double getPrice() { 24 | throw new UnsupportedOperationException(); 25 | } 26 | public boolean isVegetarian() { 27 | throw new UnsupportedOperationException(); 28 | } 29 | 30 | public void print() { 31 | throw new UnsupportedOperationException(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/composite/menu/MenuItem.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menu; 2 | 3 | import java.util.Iterator; 4 | import java.util.ArrayList; 5 | 6 | public class MenuItem extends MenuComponent { 7 | String name; 8 | String description; 9 | boolean vegetarian; 10 | double price; 11 | 12 | public MenuItem(String name, 13 | String description, 14 | boolean vegetarian, 15 | double price) 16 | { 17 | this.name = name; 18 | this.description = description; 19 | this.vegetarian = vegetarian; 20 | this.price = price; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public String getDescription() { 28 | return description; 29 | } 30 | 31 | public double getPrice() { 32 | return price; 33 | } 34 | 35 | public boolean isVegetarian() { 36 | return vegetarian; 37 | } 38 | 39 | public void print() { 40 | System.out.print(" " + getName()); 41 | if (isVegetarian()) { 42 | System.out.print("(v)"); 43 | } 44 | System.out.println(", " + getPrice()); 45 | System.out.println(" -- " + getDescription()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/headfirst/composite/menu/Waitress.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menu; 2 | 3 | import java.util.Iterator; 4 | 5 | public class Waitress { 6 | MenuComponent allMenus; 7 | 8 | public Waitress(MenuComponent allMenus) { 9 | this.allMenus = allMenus; 10 | } 11 | 12 | public void printMenu() { 13 | allMenus.print(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/composite/menuiterator/CompositeIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menuiterator; 2 | 3 | 4 | import java.util.*; 5 | 6 | public class CompositeIterator implements Iterator { 7 | Stack stack = new Stack(); 8 | 9 | public CompositeIterator(Iterator iterator) { 10 | stack.push(iterator); 11 | } 12 | 13 | public Object next() { 14 | if (hasNext()) { 15 | Iterator iterator = (Iterator) stack.peek(); 16 | MenuComponent component = (MenuComponent) iterator.next(); 17 | if (component instanceof Menu) { 18 | stack.push(component.createIterator()); 19 | } 20 | return component; 21 | } else { 22 | return null; 23 | } 24 | } 25 | 26 | public boolean hasNext() { 27 | if (stack.empty()) { 28 | return false; 29 | } else { 30 | Iterator iterator = (Iterator) stack.peek(); 31 | if (!iterator.hasNext()) { 32 | stack.pop(); 33 | return hasNext(); 34 | } else { 35 | return true; 36 | } 37 | } 38 | } 39 | 40 | public void remove() { 41 | throw new UnsupportedOperationException(); 42 | } 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /src/headfirst/composite/menuiterator/MenuComponent.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menuiterator; 2 | 3 | import java.util.*; 4 | 5 | public abstract class MenuComponent { 6 | 7 | public void add(MenuComponent menuComponent) { 8 | throw new UnsupportedOperationException(); 9 | } 10 | public void remove(MenuComponent menuComponent) { 11 | throw new UnsupportedOperationException(); 12 | } 13 | public MenuComponent getChild(int i) { 14 | throw new UnsupportedOperationException(); 15 | } 16 | 17 | public String getName() { 18 | throw new UnsupportedOperationException(); 19 | } 20 | public String getDescription() { 21 | throw new UnsupportedOperationException(); 22 | } 23 | public double getPrice() { 24 | throw new UnsupportedOperationException(); 25 | } 26 | public boolean isVegetarian() { 27 | throw new UnsupportedOperationException(); 28 | } 29 | 30 | public abstract Iterator createIterator(); 31 | 32 | public void print() { 33 | throw new UnsupportedOperationException(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/composite/menuiterator/NullIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menuiterator; 2 | 3 | import java.util.Iterator; 4 | 5 | public class NullIterator implements Iterator { 6 | 7 | public Object next() { 8 | return null; 9 | } 10 | 11 | public boolean hasNext() { 12 | return false; 13 | } 14 | 15 | public void remove() { 16 | throw new UnsupportedOperationException(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/composite/menuiterator/Waitress.java: -------------------------------------------------------------------------------- 1 | package headfirst.composite.menuiterator; 2 | 3 | import java.util.Iterator; 4 | 5 | public class Waitress { 6 | MenuComponent allMenus; 7 | 8 | public Waitress(MenuComponent allMenus) { 9 | this.allMenus = allMenus; 10 | } 11 | 12 | public void printMenu() { 13 | allMenus.print(); 14 | } 15 | 16 | public void printVegetarianMenu() { 17 | Iterator iterator = allMenus.createIterator(); 18 | 19 | System.out.println("\nVEGETARIAN MENU\n----"); 20 | while (iterator.hasNext()) { 21 | MenuComponent menuComponent = 22 | (MenuComponent)iterator.next(); 23 | try { 24 | if (menuComponent.isVegetarian()) { 25 | menuComponent.print(); 26 | } 27 | } catch (UnsupportedOperationException e) {} 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/headfirst/decorator/io/InputTest.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.io; 2 | 3 | import java.io.*; 4 | 5 | public class InputTest { 6 | public static void main(String[] args) throws IOException { 7 | int c; 8 | 9 | try { 10 | InputStream in = 11 | new LowerCaseInputStream( 12 | new BufferedInputStream( 13 | new FileInputStream("test.txt"))); 14 | 15 | while((c = in.read()) >= 0) { 16 | System.out.print((char)c); 17 | } 18 | 19 | in.close(); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/headfirst/decorator/io/LowerCaseInputStream.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.io; 2 | 3 | import java.io.*; 4 | 5 | public class LowerCaseInputStream extends FilterInputStream { 6 | 7 | public LowerCaseInputStream(InputStream in) { 8 | super(in); 9 | } 10 | 11 | public int read() throws IOException { 12 | int c = super.read(); 13 | return (c == -1 ? c : Character.toLowerCase((char)c)); 14 | } 15 | 16 | public int read(byte[] b, int offset, int len) throws IOException { 17 | int result = super.read(b, offset, len); 18 | for (int i = offset; i < offset+result; i++) { 19 | b[i] = (byte)Character.toLowerCase((char)b[i]); 20 | } 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Beverage.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public abstract class Beverage { 4 | String description = "Unknown Beverage"; 5 | 6 | public String getDescription() { 7 | return description; 8 | } 9 | 10 | public abstract double cost(); 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/CondimentDecorator.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public abstract class CondimentDecorator extends Beverage { 4 | public abstract String getDescription(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/DarkRoast.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class DarkRoast extends Beverage { 4 | public DarkRoast() { 5 | description = "Dark Roast Coffee"; 6 | } 7 | 8 | public double cost() { 9 | return .99; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Decaf.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class Decaf extends Beverage { 4 | public Decaf() { 5 | description = "Decaf Coffee"; 6 | } 7 | 8 | public double cost() { 9 | return 1.05; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Espresso.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class Espresso extends Beverage { 4 | 5 | public Espresso() { 6 | description = "Espresso"; 7 | } 8 | 9 | public double cost() { 10 | return 1.99; 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/HouseBlend.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class HouseBlend extends Beverage { 4 | public HouseBlend() { 5 | description = "House Blend Coffee"; 6 | } 7 | 8 | public double cost() { 9 | return .89; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Milk.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class Milk extends CondimentDecorator { 4 | Beverage beverage; 5 | 6 | public Milk(Beverage beverage) { 7 | this.beverage = beverage; 8 | } 9 | 10 | public String getDescription() { 11 | return beverage.getDescription() + ", Milk"; 12 | } 13 | 14 | public double cost() { 15 | return .10 + beverage.cost(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Mocha.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class Mocha extends CondimentDecorator { 4 | Beverage beverage; 5 | 6 | public Mocha(Beverage beverage) { 7 | this.beverage = beverage; 8 | } 9 | 10 | public String getDescription() { 11 | return beverage.getDescription() + ", Mocha"; 12 | } 13 | 14 | public double cost() { 15 | return .20 + beverage.cost(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Soy.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class Soy extends CondimentDecorator { 4 | Beverage beverage; 5 | 6 | public Soy(Beverage beverage) { 7 | this.beverage = beverage; 8 | } 9 | 10 | public String getDescription() { 11 | return beverage.getDescription() + ", Soy"; 12 | } 13 | 14 | public double cost() { 15 | return .15 + beverage.cost(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/StarbuzzCoffee.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class StarbuzzCoffee { 4 | 5 | public static void main(String args[]) { 6 | Beverage beverage = new Espresso(); 7 | System.out.println(beverage.getDescription() 8 | + " $" + beverage.cost()); 9 | 10 | Beverage beverage2 = new DarkRoast(); 11 | beverage2 = new Mocha(beverage2); 12 | beverage2 = new Mocha(beverage2); 13 | beverage2 = new Whip(beverage2); 14 | System.out.println(beverage2.getDescription() 15 | + " $" + beverage2.cost()); 16 | 17 | Beverage beverage3 = new HouseBlend(); 18 | beverage3 = new Soy(beverage3); 19 | beverage3 = new Mocha(beverage3); 20 | beverage3 = new Whip(beverage3); 21 | System.out.println(beverage3.getDescription() 22 | + " $" + beverage3.cost()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/headfirst/decorator/starbuzz/Whip.java: -------------------------------------------------------------------------------- 1 | package headfirst.decorator.starbuzz; 2 | 3 | public class Whip extends CondimentDecorator { 4 | Beverage beverage; 5 | 6 | public Whip(Beverage beverage) { 7 | this.beverage = beverage; 8 | } 9 | 10 | public String getDescription() { 11 | return beverage.getDescription() + ", Whip"; 12 | } 13 | 14 | public double cost() { 15 | return .10 + beverage.cost(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/facade/hometheater/HomeTheaterTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.facade.hometheater; 2 | 3 | public class HomeTheaterTestDrive { 4 | public static void main(String[] args) { 5 | Amplifier amp = new Amplifier("Top-O-Line Amplifier"); 6 | Tuner tuner = new Tuner("Top-O-Line AM/FM Tuner", amp); 7 | DvdPlayer dvd = new DvdPlayer("Top-O-Line DVD Player", amp); 8 | CdPlayer cd = new CdPlayer("Top-O-Line CD Player", amp); 9 | Projector projector = new Projector("Top-O-Line Projector", dvd); 10 | TheaterLights lights = new TheaterLights("Theater Ceiling Lights"); 11 | Screen screen = new Screen("Theater Screen"); 12 | PopcornPopper popper = new PopcornPopper("Popcorn Popper"); 13 | 14 | HomeTheaterFacade homeTheater = 15 | new HomeTheaterFacade(amp, tuner, dvd, cd, 16 | projector, screen, lights, popper); 17 | 18 | homeTheater.watchMovie("Raiders of the Lost Ark"); 19 | homeTheater.endMovie(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/headfirst/facade/hometheater/PopcornPopper.java: -------------------------------------------------------------------------------- 1 | package headfirst.facade.hometheater; 2 | 3 | public class PopcornPopper { 4 | String description; 5 | 6 | public PopcornPopper(String description) { 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 pop() { 19 | System.out.println(description + " popping popcorn!"); 20 | } 21 | 22 | 23 | public String toString() { 24 | return description; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/facade/hometheater/Projector.java: -------------------------------------------------------------------------------- 1 | package headfirst.facade.hometheater; 2 | 3 | public class Projector { 4 | String description; 5 | DvdPlayer dvdPlayer; 6 | 7 | public Projector(String description, DvdPlayer dvdPlayer) { 8 | this.description = description; 9 | this.dvdPlayer = dvdPlayer; 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 wideScreenMode() { 21 | System.out.println(description + " in widescreen mode (16x9 aspect ratio)"); 22 | } 23 | 24 | public void tvMode() { 25 | System.out.println(description + " in tv mode (4x3 aspect ratio)"); 26 | } 27 | 28 | public String toString() { 29 | return description; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/facade/hometheater/Screen.java: -------------------------------------------------------------------------------- 1 | package headfirst.facade.hometheater; 2 | 3 | public class Screen { 4 | String description; 5 | 6 | public Screen(String description) { 7 | this.description = description; 8 | } 9 | 10 | public void up() { 11 | System.out.println(description + " going up"); 12 | } 13 | 14 | public void down() { 15 | System.out.println(description + " going down"); 16 | } 17 | 18 | 19 | public String toString() { 20 | return description; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/facade/hometheater/TheaterLights.java: -------------------------------------------------------------------------------- 1 | package headfirst.facade.hometheater; 2 | 3 | public class TheaterLights { 4 | String description; 5 | 6 | public TheaterLights(String description) { 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 dim(int level) { 19 | System.out.println(description + " dimming to " + level + "%"); 20 | } 21 | 22 | public String toString() { 23 | return description; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/headfirst/facade/hometheater/Tuner.java: -------------------------------------------------------------------------------- 1 | package headfirst.facade.hometheater; 2 | 3 | public class Tuner { 4 | String description; 5 | Amplifier amplifier; 6 | double frequency; 7 | 8 | public Tuner(String description, Amplifier amplifier) { 9 | this.description = description; 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 setFrequency(double frequency) { 21 | System.out.println(description + " setting frequency to " + frequency); 22 | this.frequency = frequency; 23 | } 24 | 25 | public void setAm() { 26 | System.out.println(description + " setting AM mode"); 27 | } 28 | 29 | public void setFm() { 30 | System.out.println(description + " setting FM mode"); 31 | } 32 | 33 | public String toString() { 34 | return description; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/BlackOlives.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class BlackOlives implements Veggies { 4 | 5 | public String toString() { 6 | return "Black Olives"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Cheese.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface Cheese { 4 | public String toString(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class CheesePizza extends Pizza { 4 | PizzaIngredientFactory ingredientFactory; 5 | 6 | public CheesePizza(PizzaIngredientFactory ingredientFactory) { 7 | this.ingredientFactory = ingredientFactory; 8 | } 9 | 10 | void prepare() { 11 | System.out.println("Preparing " + name); 12 | dough = ingredientFactory.createDough(); 13 | sauce = ingredientFactory.createSauce(); 14 | cheese = ingredientFactory.createCheese(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ChicagoPizzaIngredientFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ChicagoPizzaIngredientFactory 4 | implements PizzaIngredientFactory 5 | { 6 | 7 | public Dough createDough() { 8 | return new ThickCrustDough(); 9 | } 10 | 11 | public Sauce createSauce() { 12 | return new PlumTomatoSauce(); 13 | } 14 | 15 | public Cheese createCheese() { 16 | return new MozzarellaCheese(); 17 | } 18 | 19 | public Veggies[] createVeggies() { 20 | Veggies veggies[] = { new BlackOlives(), 21 | new Spinach(), 22 | new Eggplant() }; 23 | return veggies; 24 | } 25 | 26 | public Pepperoni createPepperoni() { 27 | return new SlicedPepperoni(); 28 | } 29 | 30 | public Clams createClam() { 31 | return new FrozenClams(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ChicagoPizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ChicagoPizzaStore extends PizzaStore { 4 | 5 | protected Pizza createPizza(String item) { 6 | Pizza pizza = null; 7 | PizzaIngredientFactory ingredientFactory = 8 | new ChicagoPizzaIngredientFactory(); 9 | 10 | if (item.equals("cheese")) { 11 | 12 | pizza = new CheesePizza(ingredientFactory); 13 | pizza.setName("Chicago Style Cheese Pizza"); 14 | 15 | } else if (item.equals("veggie")) { 16 | 17 | pizza = new VeggiePizza(ingredientFactory); 18 | pizza.setName("Chicago Style Veggie Pizza"); 19 | 20 | } else if (item.equals("clam")) { 21 | 22 | pizza = new ClamPizza(ingredientFactory); 23 | pizza.setName("Chicago Style Clam Pizza"); 24 | 25 | } else if (item.equals("pepperoni")) { 26 | 27 | pizza = new PepperoniPizza(ingredientFactory); 28 | pizza.setName("Chicago Style Pepperoni Pizza"); 29 | 30 | } 31 | return pizza; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ClamPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ClamPizza extends Pizza { 4 | PizzaIngredientFactory ingredientFactory; 5 | 6 | public ClamPizza(PizzaIngredientFactory ingredientFactory) { 7 | this.ingredientFactory = ingredientFactory; 8 | } 9 | 10 | void prepare() { 11 | System.out.println("Preparing " + name); 12 | dough = ingredientFactory.createDough(); 13 | sauce = ingredientFactory.createSauce(); 14 | cheese = ingredientFactory.createCheese(); 15 | clam = ingredientFactory.createClam(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Clams.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface Clams { 4 | public String toString(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Dough.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface Dough { 4 | public String toString(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Eggplant.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class Eggplant implements Veggies { 4 | 5 | public String toString() { 6 | return "Eggplant"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/FreshClams.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class FreshClams implements Clams { 4 | 5 | public String toString() { 6 | return "Fresh Clams from Long Island Sound"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/FrozenClams.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class FrozenClams implements Clams { 4 | 5 | public String toString() { 6 | return "Frozen Clams from Chesapeake Bay"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Garlic.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class Garlic implements Veggies { 4 | 5 | public String toString() { 6 | return "Garlic"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/MarinaraSauce.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class MarinaraSauce implements Sauce { 4 | public String toString() { 5 | return "Marinara Sauce"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/MozzarellaCheese.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class MozzarellaCheese implements Cheese { 4 | 5 | public String toString() { 6 | return "Shredded Mozzarella"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Mushroom.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class Mushroom implements Veggies { 4 | 5 | public String toString() { 6 | return "Mushrooms"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/NYPizzaIngredientFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class NYPizzaIngredientFactory implements PizzaIngredientFactory { 4 | 5 | public Dough createDough() { 6 | return new ThinCrustDough(); 7 | } 8 | 9 | public Sauce createSauce() { 10 | return new MarinaraSauce(); 11 | } 12 | 13 | public Cheese createCheese() { 14 | return new ReggianoCheese(); 15 | } 16 | 17 | public Veggies[] createVeggies() { 18 | Veggies veggies[] = { new Garlic(), new Onion(), new Mushroom(), new RedPepper() }; 19 | return veggies; 20 | } 21 | 22 | public Pepperoni createPepperoni() { 23 | return new SlicedPepperoni(); 24 | } 25 | 26 | public Clams createClam() { 27 | return new FreshClams(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/NYPizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class NYPizzaStore extends PizzaStore { 4 | 5 | protected Pizza createPizza(String item) { 6 | Pizza pizza = null; 7 | PizzaIngredientFactory ingredientFactory = 8 | new NYPizzaIngredientFactory(); 9 | 10 | if (item.equals("cheese")) { 11 | 12 | pizza = new CheesePizza(ingredientFactory); 13 | pizza.setName("New York Style Cheese Pizza"); 14 | 15 | } else if (item.equals("veggie")) { 16 | 17 | pizza = new VeggiePizza(ingredientFactory); 18 | pizza.setName("New York Style Veggie Pizza"); 19 | 20 | } else if (item.equals("clam")) { 21 | 22 | pizza = new ClamPizza(ingredientFactory); 23 | pizza.setName("New York Style Clam Pizza"); 24 | 25 | } else if (item.equals("pepperoni")) { 26 | 27 | pizza = new PepperoniPizza(ingredientFactory); 28 | pizza.setName("New York Style Pepperoni Pizza"); 29 | 30 | } 31 | return pizza; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Onion.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class Onion implements Veggies { 4 | 5 | public String toString() { 6 | return "Onion"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ParmesanCheese.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ParmesanCheese implements Cheese { 4 | 5 | public String toString() { 6 | return "Shredded Parmesan"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Pepperoni.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface Pepperoni { 4 | public String toString(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class PepperoniPizza extends Pizza { 4 | PizzaIngredientFactory ingredientFactory; 5 | 6 | public PepperoniPizza(PizzaIngredientFactory ingredientFactory) { 7 | this.ingredientFactory = ingredientFactory; 8 | } 9 | 10 | void prepare() { 11 | System.out.println("Preparing " + name); 12 | dough = ingredientFactory.createDough(); 13 | sauce = ingredientFactory.createSauce(); 14 | cheese = ingredientFactory.createCheese(); 15 | veggies = ingredientFactory.createVeggies(); 16 | pepperoni = ingredientFactory.createPepperoni(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/PizzaIngredientFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface PizzaIngredientFactory { 4 | 5 | public Dough createDough(); 6 | public Sauce createSauce(); 7 | public Cheese createCheese(); 8 | public Veggies[] createVeggies(); 9 | public Pepperoni createPepperoni(); 10 | public Clams createClam(); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/PizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public abstract class PizzaStore { 4 | 5 | protected abstract Pizza createPizza(String item); 6 | 7 | public Pizza orderPizza(String type) { 8 | Pizza pizza = createPizza(type); 9 | System.out.println("--- Making a " + pizza.getName() + " ---"); 10 | pizza.prepare(); 11 | pizza.bake(); 12 | pizza.cut(); 13 | pizza.box(); 14 | return pizza; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/PizzaTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class PizzaTestDrive { 4 | 5 | public static void main(String[] args) { 6 | PizzaStore nyStore = new NYPizzaStore(); 7 | PizzaStore chicagoStore = new ChicagoPizzaStore(); 8 | 9 | Pizza pizza = nyStore.orderPizza("cheese"); 10 | System.out.println("Ethan ordered a " + pizza + "\n"); 11 | 12 | pizza = chicagoStore.orderPizza("cheese"); 13 | System.out.println("Joel ordered a " + pizza + "\n"); 14 | 15 | pizza = nyStore.orderPizza("clam"); 16 | System.out.println("Ethan ordered a " + pizza + "\n"); 17 | 18 | pizza = chicagoStore.orderPizza("clam"); 19 | System.out.println("Joel ordered a " + pizza + "\n"); 20 | 21 | pizza = nyStore.orderPizza("pepperoni"); 22 | System.out.println("Ethan ordered a " + pizza + "\n"); 23 | 24 | pizza = chicagoStore.orderPizza("pepperoni"); 25 | System.out.println("Joel ordered a " + pizza + "\n"); 26 | 27 | pizza = nyStore.orderPizza("veggie"); 28 | System.out.println("Ethan ordered a " + pizza + "\n"); 29 | 30 | pizza = chicagoStore.orderPizza("veggie"); 31 | System.out.println("Joel ordered a " + pizza + "\n"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/PlumTomatoSauce.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class PlumTomatoSauce implements Sauce { 4 | public String toString() { 5 | return "Tomato sauce with plum tomatoes"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/RedPepper.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class RedPepper implements Veggies { 4 | 5 | public String toString() { 6 | return "Red Pepper"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ReggianoCheese.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ReggianoCheese implements Cheese { 4 | 5 | public String toString() { 6 | return "Reggiano Cheese"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Sauce.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface Sauce { 4 | public String toString(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/SlicedPepperoni.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class SlicedPepperoni implements Pepperoni { 4 | 5 | public String toString() { 6 | return "Sliced Pepperoni"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Spinach.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class Spinach implements Veggies { 4 | 5 | public String toString() { 6 | return "Spinach"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ThickCrustDough.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ThickCrustDough implements Dough { 4 | public String toString() { 5 | return "ThickCrust style extra thick crust dough"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/ThinCrustDough.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class ThinCrustDough implements Dough { 4 | public String toString() { 5 | return "Thin Crust Dough"; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public class VeggiePizza extends Pizza { 4 | PizzaIngredientFactory ingredientFactory; 5 | 6 | public VeggiePizza(PizzaIngredientFactory ingredientFactory) { 7 | this.ingredientFactory = ingredientFactory; 8 | } 9 | 10 | void prepare() { 11 | System.out.println("Preparing " + name); 12 | dough = ingredientFactory.createDough(); 13 | sauce = ingredientFactory.createSauce(); 14 | cheese = ingredientFactory.createCheese(); 15 | veggies = ingredientFactory.createVeggies(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzaaf/Veggies.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzaaf; 2 | 3 | public interface Veggies { 4 | public String toString(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/ChicagoPizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class ChicagoPizzaStore extends PizzaStore { 4 | 5 | Pizza createPizza(String item) { 6 | if (item.equals("cheese")) { 7 | return new ChicagoStyleCheesePizza(); 8 | } else if (item.equals("veggie")) { 9 | return new ChicagoStyleVeggiePizza(); 10 | } else if (item.equals("clam")) { 11 | return new ChicagoStyleClamPizza(); 12 | } else if (item.equals("pepperoni")) { 13 | return new ChicagoStylePepperoniPizza(); 14 | } else return null; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/ChicagoStyleCheesePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class ChicagoStyleCheesePizza extends Pizza { 4 | 5 | public ChicagoStyleCheesePizza() { 6 | name = "Chicago Style Deep Dish Cheese Pizza"; 7 | dough = "Extra Thick Crust Dough"; 8 | sauce = "Plum Tomato Sauce"; 9 | 10 | toppings.add("Shredded Mozzarella Cheese"); 11 | } 12 | 13 | void cut() { 14 | System.out.println("Cutting the pizza into square slices"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/ChicagoStyleClamPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class ChicagoStyleClamPizza extends Pizza { 4 | public ChicagoStyleClamPizza() { 5 | name = "Chicago Style Clam Pizza"; 6 | dough = "Extra Thick Crust Dough"; 7 | sauce = "Plum Tomato Sauce"; 8 | 9 | toppings.add("Shredded Mozzarella Cheese"); 10 | toppings.add("Frozen Clams from Chesapeake Bay"); 11 | } 12 | 13 | void cut() { 14 | System.out.println("Cutting the pizza into square slices"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/ChicagoStylePepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class ChicagoStylePepperoniPizza extends Pizza { 4 | public ChicagoStylePepperoniPizza() { 5 | name = "Chicago Style Pepperoni Pizza"; 6 | dough = "Extra Thick Crust Dough"; 7 | sauce = "Plum Tomato Sauce"; 8 | 9 | toppings.add("Shredded Mozzarella Cheese"); 10 | toppings.add("Black Olives"); 11 | toppings.add("Spinach"); 12 | toppings.add("Eggplant"); 13 | toppings.add("Sliced Pepperoni"); 14 | } 15 | 16 | void cut() { 17 | System.out.println("Cutting the pizza into square slices"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/ChicagoStyleVeggiePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class ChicagoStyleVeggiePizza extends Pizza { 4 | public ChicagoStyleVeggiePizza() { 5 | name = "Chicago Deep Dish Veggie Pizza"; 6 | dough = "Extra Thick Crust Dough"; 7 | sauce = "Plum Tomato Sauce"; 8 | 9 | toppings.add("Shredded Mozzarella Cheese"); 10 | toppings.add("Black Olives"); 11 | toppings.add("Spinach"); 12 | toppings.add("Eggplant"); 13 | } 14 | 15 | void cut() { 16 | System.out.println("Cutting the pizza into square slices"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/DependentPizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class DependentPizzaStore { 4 | 5 | public Pizza createPizza(String style, String type) { 6 | Pizza pizza = null; 7 | if (style.equals("NY")) { 8 | if (type.equals("cheese")) { 9 | pizza = new NYStyleCheesePizza(); 10 | } else if (type.equals("veggie")) { 11 | pizza = new NYStyleVeggiePizza(); 12 | } else if (type.equals("clam")) { 13 | pizza = new NYStyleClamPizza(); 14 | } else if (type.equals("pepperoni")) { 15 | pizza = new NYStylePepperoniPizza(); 16 | } 17 | } else if (style.equals("Chicago")) { 18 | if (type.equals("cheese")) { 19 | pizza = new ChicagoStyleCheesePizza(); 20 | } else if (type.equals("veggie")) { 21 | pizza = new ChicagoStyleVeggiePizza(); 22 | } else if (type.equals("clam")) { 23 | pizza = new ChicagoStyleClamPizza(); 24 | } else if (type.equals("pepperoni")) { 25 | pizza = new ChicagoStylePepperoniPizza(); 26 | } 27 | } else { 28 | System.out.println("Error: invalid type of pizza"); 29 | return null; 30 | } 31 | pizza.prepare(); 32 | pizza.bake(); 33 | pizza.cut(); 34 | pizza.box(); 35 | return pizza; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/NYPizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class NYPizzaStore extends PizzaStore { 4 | 5 | Pizza createPizza(String item) { 6 | if (item.equals("cheese")) { 7 | return new NYStyleCheesePizza(); 8 | } else if (item.equals("veggie")) { 9 | return new NYStyleVeggiePizza(); 10 | } else if (item.equals("clam")) { 11 | return new NYStyleClamPizza(); 12 | } else if (item.equals("pepperoni")) { 13 | return new NYStylePepperoniPizza(); 14 | } else return null; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/NYStyleCheesePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class NYStyleCheesePizza extends Pizza { 4 | 5 | public NYStyleCheesePizza() { 6 | name = "NY Style Sauce and Cheese Pizza"; 7 | dough = "Thin Crust Dough"; 8 | sauce = "Marinara Sauce"; 9 | 10 | toppings.add("Grated Reggiano Cheese"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/NYStyleClamPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class NYStyleClamPizza extends Pizza { 4 | 5 | public NYStyleClamPizza() { 6 | name = "NY Style Clam Pizza"; 7 | dough = "Thin Crust Dough"; 8 | sauce = "Marinara Sauce"; 9 | 10 | toppings.add("Grated Reggiano Cheese"); 11 | toppings.add("Fresh Clams from Long Island Sound"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/NYStylePepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class NYStylePepperoniPizza extends Pizza { 4 | 5 | public NYStylePepperoniPizza() { 6 | name = "NY Style Pepperoni Pizza"; 7 | dough = "Thin Crust Dough"; 8 | sauce = "Marinara Sauce"; 9 | 10 | toppings.add("Grated Reggiano Cheese"); 11 | toppings.add("Sliced Pepperoni"); 12 | toppings.add("Garlic"); 13 | toppings.add("Onion"); 14 | toppings.add("Mushrooms"); 15 | toppings.add("Red Pepper"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/NYStyleVeggiePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public class NYStyleVeggiePizza extends Pizza { 4 | 5 | public NYStyleVeggiePizza() { 6 | name = "NY Style Veggie Pizza"; 7 | dough = "Thin Crust Dough"; 8 | sauce = "Marinara Sauce"; 9 | 10 | toppings.add("Grated Reggiano Cheese"); 11 | toppings.add("Garlic"); 12 | toppings.add("Onion"); 13 | toppings.add("Mushrooms"); 14 | toppings.add("Red Pepper"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzafm/PizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzafm; 2 | 3 | public abstract class PizzaStore { 4 | 5 | abstract Pizza createPizza(String item); 6 | 7 | public Pizza orderPizza(String type) { 8 | Pizza pizza = createPizza(type); 9 | System.out.println("--- Making a " + pizza.getName() + " ---"); 10 | pizza.prepare(); 11 | pizza.bake(); 12 | pizza.cut(); 13 | pizza.box(); 14 | return pizza; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/CheesePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class CheesePizza extends Pizza { 4 | public CheesePizza() { 5 | name = "Cheese Pizza"; 6 | dough = "Regular Crust"; 7 | sauce = "Marinara Pizza Sauce"; 8 | toppings.add("Fresh Mozzarella"); 9 | toppings.add("Parmesan"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/ClamPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class ClamPizza extends Pizza { 4 | public ClamPizza() { 5 | name = "Clam Pizza"; 6 | dough = "Thin crust"; 7 | sauce = "White garlic sauce"; 8 | toppings.add("Clams"); 9 | toppings.add("Grated parmesan cheese"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/PepperoniPizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class PepperoniPizza extends Pizza { 4 | public PepperoniPizza() { 5 | name = "Pepperoni Pizza"; 6 | dough = "Crust"; 7 | sauce = "Marinara sauce"; 8 | toppings.add("Sliced Pepperoni"); 9 | toppings.add("Sliced Onion"); 10 | toppings.add("Grated parmesan cheese"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/Pizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | import java.util.ArrayList; 4 | 5 | abstract public class Pizza { 6 | String name; 7 | String dough; 8 | String sauce; 9 | ArrayList toppings = new ArrayList(); 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void prepare() { 16 | System.out.println("Preparing " + name); 17 | } 18 | 19 | public void bake() { 20 | System.out.println("Baking " + name); 21 | } 22 | 23 | public void cut() { 24 | System.out.println("Cutting " + name); 25 | } 26 | 27 | public void box() { 28 | System.out.println("Boxing " + name); 29 | } 30 | 31 | public String toString() { 32 | // code to display pizza name and ingredients 33 | StringBuffer display = new StringBuffer(); 34 | display.append("---- " + name + " ----\n"); 35 | display.append(dough + "\n"); 36 | display.append(sauce + "\n"); 37 | for (int i = 0; i < toppings.size(); i++) { 38 | display.append((String )toppings.get(i) + "\n"); 39 | } 40 | return display.toString(); 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/PizzaStore.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class PizzaStore { 4 | SimplePizzaFactory factory; 5 | 6 | public PizzaStore(SimplePizzaFactory factory) { 7 | this.factory = factory; 8 | } 9 | 10 | public Pizza orderPizza(String type) { 11 | Pizza pizza; 12 | 13 | pizza = factory.createPizza(type); 14 | 15 | pizza.prepare(); 16 | pizza.bake(); 17 | pizza.cut(); 18 | pizza.box(); 19 | 20 | return pizza; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/PizzaTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class PizzaTestDrive { 4 | 5 | public static void main(String[] args) { 6 | SimplePizzaFactory factory = new SimplePizzaFactory(); 7 | PizzaStore store = new PizzaStore(factory); 8 | 9 | Pizza pizza = store.orderPizza("cheese"); 10 | System.out.println("We ordered a " + pizza.getName() + "\n"); 11 | 12 | pizza = store.orderPizza("veggie"); 13 | System.out.println("We ordered a " + pizza.getName() + "\n"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/SimplePizzaFactory.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class SimplePizzaFactory { 4 | 5 | public Pizza createPizza(String type) { 6 | Pizza pizza = null; 7 | 8 | if (type.equals("cheese")) { 9 | pizza = new CheesePizza(); 10 | } else if (type.equals("pepperoni")) { 11 | pizza = new PepperoniPizza(); 12 | } else if (type.equals("clam")) { 13 | pizza = new ClamPizza(); 14 | } else if (type.equals("veggie")) { 15 | pizza = new VeggiePizza(); 16 | } 17 | return pizza; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/factory/pizzas/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package headfirst.factory.pizzas; 2 | 3 | public class VeggiePizza extends Pizza { 4 | public VeggiePizza() { 5 | name = "Veggie Pizza"; 6 | dough = "Crust"; 7 | sauce = "Marinara sauce"; 8 | toppings.add("Shredded mozzarella"); 9 | toppings.add("Grated parmesan"); 10 | toppings.add("Diced onion"); 11 | toppings.add("Sliced mushrooms"); 12 | toppings.add("Sliced red pepper"); 13 | toppings.add("Sliced black olives"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/AlternatingDinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | import java.util.Calendar; 4 | 5 | public class AlternatingDinerMenuIterator implements Iterator { 6 | MenuItem[] list; 7 | int position; 8 | 9 | public AlternatingDinerMenuIterator(MenuItem[] list) { 10 | this.list = list; 11 | Calendar rightNow = Calendar.getInstance(); 12 | position = rightNow.DAY_OF_WEEK % 2; 13 | } 14 | public Object next() { 15 | MenuItem menuItem = list[position]; 16 | position = position + 2; 17 | return menuItem; 18 | } 19 | public boolean hasNext() { 20 | if (position >= list.length || list[position] == null) { 21 | return false; 22 | } else { 23 | return true; 24 | } 25 | } 26 | public String toString() { 27 | return "Alternating Diner Menu Iterator"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/ArrayIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | public class ArrayIterator implements Iterator { 4 | MenuItem[] items; 5 | int position = 0; 6 | 7 | public ArrayIterator(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 | } else { 21 | return true; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/ArrayListIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class ArrayListIterator implements Iterator { 6 | ArrayList items; 7 | int position = 0; 8 | 9 | public ArrayListIterator(ArrayList items) { 10 | this.items = items; 11 | } 12 | 13 | public Object next() { 14 | Object object = items.get(position); 15 | position = position + 1; 16 | return object; 17 | } 18 | 19 | public boolean hasNext() { 20 | if (position >= items.size()) { 21 | return false; 22 | } else { 23 | return true; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/DinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 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 | } else { 21 | return true; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/Iterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | public interface Iterator { 4 | boolean hasNext(); 5 | Object next(); 6 | } 7 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/Menu.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | public interface Menu { 4 | public Iterator createIterator(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/MenuItem.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | public class MenuItem { 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 | { 14 | this.name = name; 15 | this.description = description; 16 | this.vegetarian = vegetarian; 17 | this.price = price; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public double getPrice() { 29 | return price; 30 | } 31 | 32 | public boolean isVegetarian() { 33 | return vegetarian; 34 | } 35 | public String toString() { 36 | return (name + ", $" + price + "\n " + description); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermerger/PancakeHouseMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermerger; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class PancakeHouseMenuIterator implements Iterator { 6 | ArrayList items; 7 | int position = 0; 8 | 9 | public PancakeHouseMenuIterator(ArrayList items) { 10 | this.items = items; 11 | } 12 | 13 | public Object next() { 14 | Object object = items.get(position); 15 | position = position + 1; 16 | return object; 17 | } 18 | 19 | public boolean hasNext() { 20 | if (position >= items.size()) { 21 | return false; 22 | } else { 23 | return true; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergercafe/AlternatingDinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergercafe; 2 | 3 | import java.util.Iterator; 4 | import java.util.Calendar; 5 | 6 | public class AlternatingDinerMenuIterator implements Iterator { 7 | MenuItem[] items; 8 | int position; 9 | 10 | public AlternatingDinerMenuIterator(MenuItem[] items) { 11 | this.items = items; 12 | Calendar rightNow = Calendar.getInstance(); 13 | position = rightNow.DAY_OF_WEEK % 2; 14 | } 15 | public Object next() { 16 | MenuItem menuItem = items[position]; 17 | position = position + 2; 18 | return menuItem; 19 | } 20 | public boolean hasNext() { 21 | if (position >= items.length || items[position] == null) { 22 | return false; 23 | } else { 24 | return true; 25 | } 26 | } 27 | public void remove() { 28 | throw new UnsupportedOperationException( 29 | "Alternating Diner Menu Iterator does not support remove()"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergercafe/CafeMenu.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergercafe; 2 | 3 | import java.util.*; 4 | 5 | public class CafeMenu implements Menu { 6 | Hashtable menuItems = new Hashtable(); 7 | 8 | public CafeMenu() { 9 | addItem("Veggie Burger and Air Fries", 10 | "Veggie burger on a whole wheat bun, lettuce, tomato, and fries", 11 | true, 3.99); 12 | addItem("Soup of the day", 13 | "A cup of the soup of the day, with a side salad", 14 | false, 3.69); 15 | addItem("Burrito", 16 | "A large burrito, with whole pinto beans, salsa, guacamole", 17 | true, 4.29); 18 | } 19 | 20 | public void addItem(String name, String description, 21 | boolean vegetarian, double price) 22 | { 23 | MenuItem menuItem = new MenuItem(name, description, vegetarian, price); 24 | menuItems.put(menuItem.getName(), menuItem); 25 | } 26 | 27 | public Hashtable getItems() { 28 | return menuItems; 29 | } 30 | 31 | public Iterator createIterator() { 32 | return menuItems.values().iterator(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergercafe/DinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergercafe; 2 | 3 | import java.util.Iterator; 4 | 5 | public class DinerMenuIterator implements Iterator { 6 | MenuItem[] list; 7 | int position = 0; 8 | 9 | public DinerMenuIterator(MenuItem[] list) { 10 | this.list = list; 11 | } 12 | 13 | public Object next() { 14 | MenuItem menuItem = list[position]; 15 | position = position + 1; 16 | return menuItem; 17 | } 18 | 19 | public boolean hasNext() { 20 | if (position >= list.length || list[position] == null) { 21 | return false; 22 | } else { 23 | return true; 24 | } 25 | } 26 | 27 | public void remove() { 28 | if (position <= 0) { 29 | throw new IllegalStateException 30 | ("You can't remove an item until you've done at least one next()"); 31 | } 32 | if (list[position-1] != null) { 33 | for (int i = position-1; i < (list.length-1); i++) { 34 | list[i] = list[i+1]; 35 | } 36 | list[list.length-1] = null; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergercafe/Menu.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergercafe; 2 | 3 | import java.util.Iterator; 4 | 5 | public interface Menu { 6 | public Iterator createIterator(); 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergercafe/MenuItem.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergercafe; 2 | 3 | public class MenuItem { 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 | { 14 | this.name = name; 15 | this.description = description; 16 | this.vegetarian = vegetarian; 17 | this.price = price; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public double getPrice() { 29 | return price; 30 | } 31 | 32 | public boolean isVegetarian() { 33 | return vegetarian; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergercafe/MenuTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergercafe; 2 | 3 | import java.util.*; 4 | 5 | public class MenuTestDrive { 6 | public static void main(String args[]) { 7 | PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu(); 8 | DinerMenu dinerMenu = new DinerMenu(); 9 | CafeMenu cafeMenu = new CafeMenu(); 10 | 11 | Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu, cafeMenu); 12 | 13 | waitress.printMenu(); 14 | waitress.printVegetarianMenu(); 15 | 16 | System.out.println("\nCustomer asks, is the Hotdog vegetarian?"); 17 | System.out.print("Waitress says: "); 18 | if (waitress.isItemVegetarian("Hotdog")) { 19 | System.out.println("Yes"); 20 | } else { 21 | System.out.println("No"); 22 | } 23 | System.out.println("\nCustomer asks, are the Waffles vegetarian?"); 24 | System.out.print("Waitress says: "); 25 | if (waitress.isItemVegetarian("Waffles")) { 26 | System.out.println("Yes"); 27 | } else { 28 | System.out.println("No"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergeri/AlternatingDinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergeri; 2 | 3 | import java.util.Iterator; 4 | import java.util.Calendar; 5 | 6 | public class AlternatingDinerMenuIterator implements Iterator { 7 | MenuItem[] items; 8 | int position; 9 | 10 | public AlternatingDinerMenuIterator(MenuItem[] items) { 11 | this.items = items; 12 | Calendar rightNow = Calendar.getInstance(); 13 | position = rightNow.DAY_OF_WEEK % 2; 14 | } 15 | public Object next() { 16 | MenuItem menuItem = items[position]; 17 | position = position + 2; 18 | return menuItem; 19 | } 20 | public boolean hasNext() { 21 | if (position >= items.length || items[position] == null) { 22 | return false; 23 | } else { 24 | return true; 25 | } 26 | } 27 | public void remove() { 28 | throw new UnsupportedOperationException( 29 | "Alternating Diner Menu Iterator does not support remove()"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergeri/DinerMenuIterator.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergeri; 2 | 3 | import java.util.Iterator; 4 | 5 | public class DinerMenuIterator implements Iterator { 6 | MenuItem[] list; 7 | int position = 0; 8 | 9 | public DinerMenuIterator(MenuItem[] list) { 10 | this.list = list; 11 | } 12 | 13 | public Object next() { 14 | MenuItem menuItem = list[position]; 15 | position = position + 1; 16 | return menuItem; 17 | } 18 | 19 | public boolean hasNext() { 20 | if (position >= list.length || list[position] == null) { 21 | return false; 22 | } else { 23 | return true; 24 | } 25 | } 26 | 27 | public void remove() { 28 | if (position <= 0) { 29 | throw new IllegalStateException 30 | ("You can't remove an item until you've done at least one next()"); 31 | } 32 | if (list[position-1] != null) { 33 | for (int i = position-1; i < (list.length-1); i++) { 34 | list[i] = list[i+1]; 35 | } 36 | list[list.length-1] = null; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergeri/Menu.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergeri; 2 | 3 | import java.util.Iterator; 4 | 5 | public interface Menu { 6 | public Iterator createIterator(); 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergeri/MenuItem.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergeri; 2 | 3 | public class MenuItem { 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 | { 14 | this.name = name; 15 | this.description = description; 16 | this.vegetarian = vegetarian; 17 | this.price = price; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public double getPrice() { 29 | return price; 30 | } 31 | 32 | public boolean isVegetarian() { 33 | return vegetarian; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/iterator/dinermergeri/MenuTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.dinermergeri; 2 | 3 | import java.util.*; 4 | 5 | public class MenuTestDrive { 6 | public static void main(String args[]) { 7 | PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu(); 8 | DinerMenu dinerMenu = new DinerMenu(); 9 | Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu); 10 | waitress.printMenu(); 11 | waitress.printVegetarianMenu(); 12 | 13 | System.out.println("\nCustomer asks, is the Hotdog vegetarian?"); 14 | System.out.print("Waitress says: "); 15 | if (waitress.isItemVegetarian("Hotdog")) { 16 | System.out.println("Yes"); 17 | } else { 18 | System.out.println("No"); 19 | } 20 | System.out.println("\nCustomer asks, are the Waffles vegetarian?"); 21 | System.out.print("Waitress says: "); 22 | if (waitress.isItemVegetarian("Waffles")) { 23 | System.out.println("Yes"); 24 | } else { 25 | System.out.println("No"); 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/iterator/transition/Menu.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.transition; 2 | 3 | import java.util.Iterator; 4 | 5 | public interface Menu { 6 | public Iterator createIterator(); 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/iterator/transition/MenuItem.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.transition; 2 | 3 | public class MenuItem { 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 | { 14 | this.name = name; 15 | this.description = description; 16 | this.vegetarian = vegetarian; 17 | this.price = price; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public String getDescription() { 25 | return description; 26 | } 27 | 28 | public double getPrice() { 29 | return price; 30 | } 31 | 32 | public boolean isVegetarian() { 33 | return vegetarian; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/iterator/transition/Waitress.java: -------------------------------------------------------------------------------- 1 | package headfirst.iterator.transition; 2 | import java.util.*; 3 | 4 | 5 | public class Waitress { 6 | ArrayList menus; 7 | 8 | 9 | public Waitress(ArrayList menus) { 10 | this.menus = menus; 11 | } 12 | 13 | public void printMenu() { 14 | Iterator menuIterator = menus.iterator(); 15 | while(menuIterator.hasNext()) { 16 | Menu menu = (Menu)menuIterator.next(); 17 | printMenu(menu.createIterator()); 18 | } 19 | } 20 | 21 | void printMenu(Iterator iterator) { 22 | while (iterator.hasNext()) { 23 | MenuItem menuItem = (MenuItem)iterator.next(); 24 | System.out.print(menuItem.getName() + ", "); 25 | System.out.print(menuItem.getPrice() + " -- "); 26 | System.out.println(menuItem.getDescription()); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/CurrentConditionsDisplay.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | public class CurrentConditionsDisplay implements Observer, DisplayElement { 4 | private float temperature; 5 | private float humidity; 6 | private Subject weatherData; 7 | 8 | public CurrentConditionsDisplay(Subject weatherData) { 9 | this.weatherData = weatherData; 10 | weatherData.registerObserver(this); 11 | } 12 | 13 | public void update(float temperature, float humidity, float pressure) { 14 | this.temperature = temperature; 15 | this.humidity = humidity; 16 | display(); 17 | } 18 | 19 | public void display() { 20 | System.out.println("Current conditions: " + temperature 21 | + "F degrees and " + humidity + "% humidity"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/DisplayElement.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | public interface DisplayElement { 4 | public void display(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/ForecastDisplay.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | import java.util.*; 4 | 5 | public class ForecastDisplay implements Observer, DisplayElement { 6 | private float currentPressure = 29.92f; 7 | private float lastPressure; 8 | private WeatherData weatherData; 9 | 10 | public ForecastDisplay(WeatherData weatherData) { 11 | this.weatherData = weatherData; 12 | weatherData.registerObserver(this); 13 | } 14 | 15 | public void update(float temp, float humidity, float pressure) { 16 | lastPressure = currentPressure; 17 | currentPressure = pressure; 18 | 19 | display(); 20 | } 21 | 22 | public void display() { 23 | System.out.print("Forecast: "); 24 | if (currentPressure > lastPressure) { 25 | System.out.println("Improving weather on the way!"); 26 | } else if (currentPressure == lastPressure) { 27 | System.out.println("More of the same"); 28 | } else if (currentPressure < lastPressure) { 29 | System.out.println("Watch out for cooler, rainy weather"); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/Observer.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | public interface Observer { 4 | public void update(float temp, float humidity, float pressure); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/StatisticsDisplay.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | import java.util.*; 4 | 5 | public class StatisticsDisplay implements Observer, DisplayElement { 6 | private float maxTemp = 0.0f; 7 | private float minTemp = 200; 8 | private float tempSum= 0.0f; 9 | private int numReadings; 10 | private WeatherData weatherData; 11 | 12 | public StatisticsDisplay(WeatherData weatherData) { 13 | this.weatherData = weatherData; 14 | weatherData.registerObserver(this); 15 | } 16 | 17 | public void update(float temp, float humidity, float pressure) { 18 | tempSum += temp; 19 | numReadings++; 20 | 21 | if (temp > maxTemp) { 22 | maxTemp = temp; 23 | } 24 | 25 | if (temp < minTemp) { 26 | minTemp = temp; 27 | } 28 | 29 | display(); 30 | } 31 | 32 | public void display() { 33 | System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings) 34 | + "/" + maxTemp + "/" + minTemp); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/Subject.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | public interface Subject { 4 | public void registerObserver(Observer o); 5 | public void removeObserver(Observer o); 6 | public void notifyObservers(); 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/WeatherStation.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | import java.util.*; 4 | 5 | public class WeatherStation { 6 | 7 | public static void main(String[] args) { 8 | WeatherData weatherData = new WeatherData(); 9 | 10 | CurrentConditionsDisplay currentDisplay = 11 | new CurrentConditionsDisplay(weatherData); 12 | StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 13 | ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 14 | 15 | weatherData.setMeasurements(80, 65, 30.4f); 16 | weatherData.setMeasurements(82, 70, 29.2f); 17 | weatherData.setMeasurements(78, 90, 29.2f); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/headfirst/observer/weather/WeatherStationHeatIndex.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weather; 2 | 3 | import java.util.*; 4 | 5 | public class WeatherStationHeatIndex { 6 | 7 | public static void main(String[] args) { 8 | WeatherData weatherData = new WeatherData(); 9 | CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); 10 | StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 11 | ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 12 | HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData); 13 | 14 | weatherData.setMeasurements(80, 65, 30.4f); 15 | weatherData.setMeasurements(82, 70, 29.2f); 16 | weatherData.setMeasurements(78, 90, 29.2f); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/CurrentConditionsDisplay.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | import java.util.Observable; 4 | import java.util.Observer; 5 | 6 | public class CurrentConditionsDisplay implements Observer, DisplayElement { 7 | Observable observable; 8 | private float temperature; 9 | private float humidity; 10 | 11 | public CurrentConditionsDisplay(Observable observable) { 12 | this.observable = observable; 13 | observable.addObserver(this); 14 | } 15 | 16 | public void update(Observable obs, Object arg) { 17 | if (obs instanceof WeatherData) { 18 | WeatherData weatherData = (WeatherData)obs; 19 | this.temperature = weatherData.getTemperature(); 20 | this.humidity = weatherData.getHumidity(); 21 | display(); 22 | } 23 | } 24 | 25 | public void display() { 26 | System.out.println("Current conditions: " + temperature 27 | + "F degrees and " + humidity + "% humidity"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/DisplayElement.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | public interface DisplayElement { 4 | public void display(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/ForecastDisplay.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | import java.util.Observable; 4 | import java.util.Observer; 5 | 6 | public class ForecastDisplay implements Observer, DisplayElement { 7 | private float currentPressure = 29.92f; 8 | private float lastPressure; 9 | 10 | public ForecastDisplay(Observable observable) { 11 | observable.addObserver(this); 12 | } 13 | 14 | public void update(Observable observable, Object arg) { 15 | if (observable instanceof WeatherData) { 16 | WeatherData weatherData = (WeatherData)observable; 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 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/StatisticsDisplay.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | import java.util.Observable; 4 | import java.util.Observer; 5 | 6 | public class StatisticsDisplay implements Observer, DisplayElement { 7 | private float maxTemp = 0.0f; 8 | private float minTemp = 200; 9 | private float tempSum= 0.0f; 10 | private int numReadings; 11 | 12 | public StatisticsDisplay(Observable observable) { 13 | observable.addObserver(this); 14 | } 15 | 16 | public void update(Observable observable, Object arg) { 17 | if (observable instanceof WeatherData) { 18 | WeatherData weatherData = (WeatherData)observable; 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 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/WeatherData.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | import java.util.Observable; 4 | import java.util.Observer; 5 | 6 | public class WeatherData extends Observable { 7 | private float temperature; 8 | private float humidity; 9 | private float pressure; 10 | 11 | public WeatherData() { } 12 | 13 | public void measurementsChanged() { 14 | setChanged(); 15 | notifyObservers(); 16 | } 17 | 18 | public void setMeasurements(float temperature, float humidity, float pressure) { 19 | this.temperature = temperature; 20 | this.humidity = humidity; 21 | this.pressure = pressure; 22 | measurementsChanged(); 23 | } 24 | 25 | public float getTemperature() { 26 | return temperature; 27 | } 28 | 29 | public float getHumidity() { 30 | return humidity; 31 | } 32 | 33 | public float getPressure() { 34 | return pressure; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/WeatherStation.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | public class WeatherStation { 4 | 5 | public static void main(String[] args) { 6 | WeatherData weatherData = new WeatherData(); 7 | CurrentConditionsDisplay currentConditions = new CurrentConditionsDisplay(weatherData); 8 | StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 9 | ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 10 | 11 | weatherData.setMeasurements(80, 65, 30.4f); 12 | weatherData.setMeasurements(82, 70, 29.2f); 13 | weatherData.setMeasurements(78, 90, 29.2f); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/observer/weatherobservable/WeatherStationHeatIndex.java: -------------------------------------------------------------------------------- 1 | package headfirst.observer.weatherobservable; 2 | 3 | public class WeatherStationHeatIndex { 4 | 5 | public static void main(String[] args) { 6 | WeatherData weatherData = new WeatherData(); 7 | CurrentConditionsDisplay currentConditions = new CurrentConditionsDisplay(weatherData); 8 | StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); 9 | ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); 10 | HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData); 11 | 12 | weatherData.setMeasurements(80, 65, 30.4f); 13 | weatherData.setMeasurements(82, 70, 29.2f); 14 | weatherData.setMeasurements(78, 90, 29.2f); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/GumballMachineRemote.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | import java.rmi.*; 4 | 5 | public interface GumballMachineRemote extends Remote { 6 | public int getCount() throws RemoteException; 7 | public String getLocation() throws RemoteException; 8 | public State getState() throws RemoteException; 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | import java.rmi.*; 3 | 4 | public class GumballMachineTestDrive { 5 | 6 | public static void main(String[] args) { 7 | GumballMachineRemote gumballMachine = null; 8 | int count; 9 | 10 | if (args.length < 2) { 11 | System.out.println("GumballMachine "); 12 | System.exit(1); 13 | } 14 | 15 | try { 16 | count = Integer.parseInt(args[1]); 17 | 18 | gumballMachine = 19 | new GumballMachine(args[0], count); 20 | Naming.rebind("//" + args[0] + "/gumballmachine", gumballMachine); 21 | } catch (Exception e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/GumballMonitor.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | import java.rmi.*; 4 | 5 | public class GumballMonitor { 6 | GumballMachineRemote machine; 7 | 8 | public GumballMonitor(GumballMachineRemote machine) { 9 | this.machine = machine; 10 | } 11 | 12 | public void report() { 13 | try { 14 | System.out.println("Gumball Machine: " + machine.getLocation()); 15 | System.out.println("Current inventory: " + machine.getCount() + " gumballs"); 16 | System.out.println("Current state: " + machine.getState()); 17 | } catch (RemoteException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/GumballMonitorTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | import java.rmi.*; 4 | 5 | public class GumballMonitorTestDrive { 6 | 7 | public static void main(String[] args) { 8 | String[] location = {"rmi://santafe.mightygumball.com/gumballmachine", 9 | "rmi://boulder.mightygumball.com/gumballmachine", 10 | "rmi://seattle.mightygumball.com/gumballmachine"}; 11 | 12 | if (args.length >= 0) 13 | { 14 | location = new String[1]; 15 | location[0] = "rmi://" + args[0] + "/gumballmachine"; 16 | } 17 | 18 | GumballMonitor[] monitor = new GumballMonitor[location.length]; 19 | 20 | 21 | 22 | for (int i=0;i < location.length; i++) { 23 | try { 24 | GumballMachineRemote machine = 25 | (GumballMachineRemote) Naming.lookup(location[i]); 26 | monitor[i] = new GumballMonitor(machine); 27 | System.out.println(monitor[i]); 28 | } catch (Exception e) { 29 | e.printStackTrace(); 30 | } 31 | } 32 | 33 | for(int i=0; i < monitor.length; i++) { 34 | monitor[i].report(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | import java.util.Random; 4 | 5 | public class HasQuarterState implements State { 6 | Random randomWinner = new Random(System.currentTimeMillis()); 7 | transient GumballMachine gumballMachine; 8 | 9 | public HasQuarterState(GumballMachine gumballMachine) { 10 | this.gumballMachine = gumballMachine; 11 | } 12 | 13 | public void insertQuarter() { 14 | System.out.println("You can't insert another quarter"); 15 | } 16 | 17 | public void ejectQuarter() { 18 | System.out.println("Quarter returned"); 19 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 20 | } 21 | 22 | public void turnCrank() { 23 | System.out.println("You turned..."); 24 | int winner = randomWinner.nextInt(10); 25 | if (winner == 0) { 26 | gumballMachine.setState(gumballMachine.getWinnerState()); 27 | } else { 28 | gumballMachine.setState(gumballMachine.getSoldState()); 29 | } 30 | } 31 | 32 | public void dispense() { 33 | System.out.println("No gumball dispensed"); 34 | } 35 | 36 | public String toString() { 37 | return "waiting for turn of crank"; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | public class NoQuarterState implements State { 4 | transient GumballMachine gumballMachine; 5 | 6 | public NoQuarterState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You inserted a quarter"); 12 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("You haven't inserted a quarter"); 17 | } 18 | 19 | public void turnCrank() { 20 | System.out.println("You turned, but there's no quarter"); 21 | } 22 | 23 | public void dispense() { 24 | System.out.println("You need to pay first"); 25 | } 26 | 27 | public String toString() { 28 | return "waiting for quarter"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/SoldOutState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | public class SoldOutState implements State { 4 | transient GumballMachine gumballMachine; 5 | 6 | public SoldOutState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You can't insert a quarter, the machine is sold out"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("You turned, but there are no gumballs"); 20 | } 21 | 22 | public void dispense() { 23 | System.out.println("No gumball dispensed"); 24 | } 25 | 26 | public String toString() { 27 | return "sold out"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/SoldState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | public class SoldState implements State { 4 | transient GumballMachine gumballMachine; 5 | 6 | public SoldState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("Please wait, we're already giving you a gumball"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("Sorry, you already turned the crank"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("Turning twice doesn't get you another gumball!"); 20 | } 21 | 22 | public void dispense() { 23 | gumballMachine.releaseBall(); 24 | if (gumballMachine.getCount() > 0) { 25 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 26 | } else { 27 | System.out.println("Oops, out of gumballs!"); 28 | gumballMachine.setState(gumballMachine.getSoldOutState()); 29 | } 30 | } 31 | 32 | public String toString() { 33 | return "dispensing a gumball"; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumball/State.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumball; 2 | 3 | import java.io.*; 4 | 5 | public interface State extends Serializable { 6 | public void insertQuarter(); 7 | public void ejectQuarter(); 8 | public void turnCrank(); 9 | public void dispense(); 10 | } 11 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumballmonitor/GumballMonitor.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumballmonitor; 2 | 3 | public class GumballMonitor { 4 | GumballMachine machine; 5 | 6 | public GumballMonitor(GumballMachine machine) { 7 | this.machine = machine; 8 | } 9 | 10 | public void report() { 11 | System.out.println("Gumball Machine: " + machine.getLocation()); 12 | System.out.println("Current inventory: " + machine.getCount() + " gumballs"); 13 | System.out.println("Current state: " + machine.getState()); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumballmonitor/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumballmonitor; 2 | 3 | 4 | import java.util.Random; 5 | 6 | public class HasQuarterState implements State { 7 | Random randomWinner = new Random(System.currentTimeMillis()); 8 | GumballMachine gumballMachine; 9 | 10 | public HasQuarterState(GumballMachine gumballMachine) { 11 | this.gumballMachine = gumballMachine; 12 | } 13 | 14 | public void insertQuarter() { 15 | System.out.println("You can't insert another quarter"); 16 | } 17 | 18 | public void ejectQuarter() { 19 | System.out.println("Quarter returned"); 20 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 21 | } 22 | 23 | public void turnCrank() { 24 | System.out.println("You turned..."); 25 | int winner = randomWinner.nextInt(10); 26 | if (winner == 0) { 27 | gumballMachine.setState(gumballMachine.getWinnerState()); 28 | } else { 29 | gumballMachine.setState(gumballMachine.getSoldState()); 30 | } 31 | } 32 | 33 | public void dispense() { 34 | System.out.println("No gumball dispensed"); 35 | } 36 | 37 | public String toString() { 38 | return "waiting for turn of crank"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumballmonitor/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumballmonitor; 2 | 3 | public class NoQuarterState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public NoQuarterState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You inserted a quarter"); 12 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("You haven't inserted a quarter"); 17 | } 18 | 19 | public void turnCrank() { 20 | System.out.println("You turned, but there's no quarter"); 21 | } 22 | 23 | public void dispense() { 24 | System.out.println("You need to pay first"); 25 | } 26 | 27 | public String toString() { 28 | return "waiting for quarter"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumballmonitor/SoldOutState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumballmonitor; 2 | 3 | public class SoldOutState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public SoldOutState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You can't insert a quarter, the machine is sold out"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("You turned, but there are no gumballs"); 20 | } 21 | 22 | public void dispense() { 23 | System.out.println("No gumball dispensed"); 24 | } 25 | 26 | public String toString() { 27 | return "sold out"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumballmonitor/SoldState.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumballmonitor; 2 | 3 | public class SoldState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public SoldState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("Please wait, we're already giving you a gumball"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("Sorry, you already turned the crank"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("Turning twice doesn't get you another gumball!"); 20 | } 21 | 22 | public void dispense() { 23 | gumballMachine.releaseBall(); 24 | try { 25 | if (gumballMachine.getCount() > 0) { 26 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 27 | } else { 28 | System.out.println("Oops, out of gumballs!"); 29 | gumballMachine.setState(gumballMachine.getSoldOutState()); 30 | } 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | public String toString() { 37 | return "dispensing a gumball"; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/proxy/gumballmonitor/State.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.gumballmonitor; 2 | 3 | import java.io.*; 4 | 5 | public interface State extends Serializable { 6 | 7 | public void insertQuarter(); 8 | public void ejectQuarter(); 9 | public void turnCrank(); 10 | public void dispense(); 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/proxy/javaproxy/NonOwnerInvocationHandler.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.javaproxy; 2 | 3 | import java.lang.reflect.*; 4 | 5 | public class NonOwnerInvocationHandler implements InvocationHandler { 6 | PersonBean person; 7 | 8 | public NonOwnerInvocationHandler(PersonBean person) { 9 | this.person = person; 10 | } 11 | 12 | public Object invoke(Object proxy, Method method, Object[] args) 13 | throws IllegalAccessException { 14 | 15 | try { 16 | if (method.getName().startsWith("get")) { 17 | return method.invoke(person, args); 18 | } else if (method.getName().equals("setHotOrNotRating")) { 19 | return method.invoke(person, args); 20 | } else if (method.getName().startsWith("set")) { 21 | throw new IllegalAccessException(); 22 | } 23 | } catch (InvocationTargetException e) { 24 | e.printStackTrace(); 25 | } 26 | return null; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/headfirst/proxy/javaproxy/OwnerInvocationHandler.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.javaproxy; 2 | 3 | import java.lang.reflect.*; 4 | 5 | public class OwnerInvocationHandler implements InvocationHandler { 6 | PersonBean person; 7 | 8 | public OwnerInvocationHandler(PersonBean person) { 9 | this.person = person; 10 | } 11 | 12 | public Object invoke(Object proxy, Method method, Object[] args) 13 | throws IllegalAccessException { 14 | 15 | try { 16 | if (method.getName().startsWith("get")) { 17 | return method.invoke(person, args); 18 | } else if (method.getName().equals("setHotOrNotRating")) { 19 | throw new IllegalAccessException(); 20 | } else if (method.getName().startsWith("set")) { 21 | return method.invoke(person, args); 22 | } 23 | } catch (InvocationTargetException e) { 24 | e.printStackTrace(); 25 | } 26 | return null; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/headfirst/proxy/javaproxy/PersonBean.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.javaproxy; 2 | 3 | public interface PersonBean { 4 | 5 | String getName(); 6 | String getGender(); 7 | String getInterests(); 8 | int getHotOrNotRating(); 9 | 10 | void setName(String name); 11 | void setGender(String gender); 12 | void setInterests(String interests); 13 | void setHotOrNotRating(int rating); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/headfirst/proxy/javaproxy/PersonBeanImpl.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.javaproxy; 2 | 3 | public class PersonBeanImpl implements PersonBean { 4 | String name; 5 | String gender; 6 | String interests; 7 | int rating; 8 | int ratingCount = 0; 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public String getGender() { 15 | return gender; 16 | } 17 | 18 | public String getInterests() { 19 | return interests; 20 | } 21 | 22 | public int getHotOrNotRating() { 23 | if (ratingCount == 0) return 0; 24 | return (rating/ratingCount); 25 | } 26 | 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public void setGender(String gender) { 33 | this.gender = gender; 34 | } 35 | 36 | public void setInterests(String interests) { 37 | this.interests = interests; 38 | } 39 | 40 | public void setHotOrNotRating(int rating) { 41 | this.rating += rating; 42 | ratingCount++; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/headfirst/proxy/virtualproxy/ImageComponent.java: -------------------------------------------------------------------------------- 1 | package headfirst.proxy.virtualproxy; 2 | 3 | import java.awt.*; 4 | import javax.swing.*; 5 | 6 | class ImageComponent extends JComponent { 7 | private Icon icon; 8 | 9 | public ImageComponent(Icon icon) { 10 | this.icon = icon; 11 | } 12 | 13 | public void setIcon(Icon icon) { 14 | this.icon = icon; 15 | } 16 | 17 | public void paintComponent(Graphics g) { 18 | super.paintComponent(g); 19 | int w = icon.getIconWidth(); 20 | int h = icon.getIconHeight(); 21 | int x = (800 - w)/2; 22 | int y = (600 - h)/2; 23 | icon.paintIcon(this, g, x, y); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/headfirst/singleton/chocolate/ChocolateController.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.chocolate; 2 | 3 | public class ChocolateController { 4 | public static void main(String args[]) { 5 | ChocolateBoiler boiler = ChocolateBoiler.getInstance(); 6 | boiler.fill(); 7 | boiler.boil(); 8 | boiler.drain(); 9 | 10 | // will return the existing instance 11 | ChocolateBoiler boiler2 = ChocolateBoiler.getInstance(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/singleton/classic/Singleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.classic; 2 | 3 | // NOTE: This is not thread safe! 4 | 5 | public class Singleton { 6 | private static Singleton uniqueInstance; 7 | 8 | // other useful instance variables here 9 | 10 | private Singleton() {} 11 | 12 | public static Singleton getInstance() { 13 | if (uniqueInstance == null) { 14 | uniqueInstance = new Singleton(); 15 | } 16 | return uniqueInstance; 17 | } 18 | 19 | // other useful methods here 20 | } 21 | -------------------------------------------------------------------------------- /src/headfirst/singleton/dcl/Singleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.dcl; 2 | 3 | // 4 | // Danger! This implementation of Singleton not 5 | // guaranteed to work prior to Java 5 6 | // 7 | 8 | public class Singleton { 9 | private volatile static Singleton uniqueInstance; 10 | 11 | private Singleton() {} 12 | 13 | public static Singleton getInstance() { 14 | if (uniqueInstance == null) { 15 | synchronized (Singleton.class) { 16 | if (uniqueInstance == null) { 17 | uniqueInstance = new Singleton(); 18 | } 19 | } 20 | } 21 | return uniqueInstance; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/headfirst/singleton/dcl/SingletonClient.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.dcl; 2 | 3 | public class SingletonClient { 4 | public static void main(String[] args) { 5 | Singleton singleton = Singleton.getInstance(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/singleton/stat/Singleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.stat; 2 | 3 | public class Singleton { 4 | private static Singleton uniqueInstance = new Singleton(); 5 | 6 | private Singleton() {} 7 | 8 | public static Singleton getInstance() { 9 | return uniqueInstance; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/singleton/stat/SingletonClient.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.stat; 2 | 3 | public class SingletonClient { 4 | public static void main(String[] args) { 5 | Singleton singleton = Singleton.getInstance(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/singleton/subclass/CoolerSingleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.subclass; 2 | 3 | public class CoolerSingleton extends Singleton { 4 | // useful instance variables here 5 | protected static Singleton uniqueInstance; 6 | 7 | private CoolerSingleton() { 8 | super(); 9 | } 10 | 11 | // useful methods here 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/singleton/subclass/HotterSingleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.subclass; 2 | 3 | public class HotterSingleton extends Singleton { 4 | // useful instance variables here 5 | 6 | private HotterSingleton() { 7 | super(); 8 | } 9 | 10 | // useful methods here 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/singleton/subclass/Singleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.subclass; 2 | 3 | public class Singleton { 4 | protected static Singleton uniqueInstance; 5 | 6 | // other useful instance variables here 7 | 8 | protected Singleton() {} 9 | 10 | public static synchronized Singleton getInstance() { 11 | if (uniqueInstance == null) { 12 | uniqueInstance = new Singleton(); 13 | } 14 | return uniqueInstance; 15 | } 16 | 17 | // other useful methods here 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/singleton/subclass/SingletonTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.subclass; 2 | 3 | public class SingletonTestDrive { 4 | public static void main(String[] args) { 5 | Singleton foo = CoolerSingleton.getInstance(); 6 | Singleton bar = HotterSingleton.getInstance(); 7 | System.out.println(foo); 8 | System.out.println(bar); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/headfirst/singleton/threadsafe/Singleton.java: -------------------------------------------------------------------------------- 1 | package headfirst.singleton.threadsafe; 2 | 3 | public class Singleton { 4 | private static Singleton uniqueInstance; 5 | 6 | // other useful instance variables here 7 | 8 | private Singleton() {} 9 | 10 | public static synchronized Singleton getInstance() { 11 | if (uniqueInstance == null) { 12 | uniqueInstance = new Singleton(); 13 | } 14 | return uniqueInstance; 15 | } 16 | 17 | // other useful methods here 18 | } 19 | -------------------------------------------------------------------------------- /src/headfirst/state/gumball/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumball; 2 | 3 | public class GumballMachineTestDrive { 4 | 5 | public static void main(String[] args) { 6 | GumballMachine gumballMachine = new GumballMachine(5); 7 | 8 | System.out.println(gumballMachine); 9 | 10 | gumballMachine.insertQuarter(); 11 | gumballMachine.turnCrank(); 12 | 13 | System.out.println(gumballMachine); 14 | 15 | gumballMachine.insertQuarter(); 16 | gumballMachine.ejectQuarter(); 17 | gumballMachine.turnCrank(); 18 | 19 | System.out.println(gumballMachine); 20 | 21 | gumballMachine.insertQuarter(); 22 | gumballMachine.turnCrank(); 23 | gumballMachine.insertQuarter(); 24 | gumballMachine.turnCrank(); 25 | gumballMachine.ejectQuarter(); 26 | 27 | System.out.println(gumballMachine); 28 | 29 | gumballMachine.insertQuarter(); 30 | gumballMachine.insertQuarter(); 31 | gumballMachine.turnCrank(); 32 | gumballMachine.insertQuarter(); 33 | gumballMachine.turnCrank(); 34 | gumballMachine.insertQuarter(); 35 | gumballMachine.turnCrank(); 36 | 37 | System.out.println(gumballMachine); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstate/GumballMachineTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstate; 2 | 3 | public class GumballMachineTestDrive { 4 | 5 | public static void main(String[] args) { 6 | GumballMachine gumballMachine = new GumballMachine(5); 7 | 8 | System.out.println(gumballMachine); 9 | 10 | gumballMachine.insertQuarter(); 11 | gumballMachine.turnCrank(); 12 | 13 | System.out.println(gumballMachine); 14 | 15 | gumballMachine.insertQuarter(); 16 | gumballMachine.turnCrank(); 17 | gumballMachine.insertQuarter(); 18 | gumballMachine.turnCrank(); 19 | 20 | System.out.println(gumballMachine); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstate/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstate; 2 | 3 | import java.util.Random; 4 | 5 | public class HasQuarterState implements State { 6 | GumballMachine gumballMachine; 7 | 8 | public HasQuarterState(GumballMachine gumballMachine) { 9 | this.gumballMachine = gumballMachine; 10 | } 11 | 12 | public void insertQuarter() { 13 | System.out.println("You can't insert another quarter"); 14 | } 15 | 16 | public void ejectQuarter() { 17 | System.out.println("Quarter returned"); 18 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 19 | } 20 | 21 | public void turnCrank() { 22 | System.out.println("You turned..."); 23 | gumballMachine.setState(gumballMachine.getSoldState()); 24 | } 25 | 26 | public void dispense() { 27 | System.out.println("No gumball dispensed"); 28 | } 29 | 30 | public String toString() { 31 | return "waiting for turn of crank"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstate/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstate; 2 | 3 | public class NoQuarterState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public NoQuarterState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You inserted a quarter"); 12 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("You haven't inserted a quarter"); 17 | } 18 | 19 | public void turnCrank() { 20 | System.out.println("You turned, but there's no quarter"); 21 | } 22 | 23 | public void dispense() { 24 | System.out.println("You need to pay first"); 25 | } 26 | 27 | public String toString() { 28 | return "waiting for quarter"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstate/SoldOutState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstate; 2 | 3 | public class SoldOutState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public SoldOutState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You can't insert a quarter, the machine is sold out"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("You turned, but there are no gumballs"); 20 | } 21 | 22 | public void dispense() { 23 | System.out.println("No gumball dispensed"); 24 | } 25 | 26 | public String toString() { 27 | return "sold out"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstate/SoldState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstate; 2 | 3 | public class SoldState implements State { 4 | 5 | GumballMachine gumballMachine; 6 | 7 | public SoldState(GumballMachine gumballMachine) { 8 | this.gumballMachine = gumballMachine; 9 | } 10 | 11 | public void insertQuarter() { 12 | System.out.println("Please wait, we're already giving you a gumball"); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("Sorry, you already turned the crank"); 17 | } 18 | 19 | public void turnCrank() { 20 | System.out.println("Turning twice doesn't get you another gumball!"); 21 | } 22 | 23 | public void dispense() { 24 | gumballMachine.releaseBall(); 25 | if (gumballMachine.getCount() > 0) { 26 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 27 | } else { 28 | System.out.println("Oops, out of gumballs!"); 29 | gumballMachine.setState(gumballMachine.getSoldOutState()); 30 | } 31 | } 32 | 33 | public String toString() { 34 | return "dispensing a gumball"; 35 | } 36 | } 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstate/State.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstate; 2 | 3 | public interface State { 4 | 5 | public void insertQuarter(); 6 | public void ejectQuarter(); 7 | public void turnCrank(); 8 | public void dispense(); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstatewinner/HasQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstatewinner; 2 | 3 | import java.util.Random; 4 | 5 | public class HasQuarterState implements State { 6 | Random randomWinner = new Random(System.currentTimeMillis()); 7 | GumballMachine gumballMachine; 8 | 9 | public HasQuarterState(GumballMachine gumballMachine) { 10 | this.gumballMachine = gumballMachine; 11 | } 12 | 13 | public void insertQuarter() { 14 | System.out.println("You can't insert another quarter"); 15 | } 16 | 17 | public void ejectQuarter() { 18 | System.out.println("Quarter returned"); 19 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 20 | } 21 | 22 | public void turnCrank() { 23 | System.out.println("You turned..."); 24 | int winner = randomWinner.nextInt(10); 25 | if ((winner == 0) && (gumballMachine.getCount() > 1)) { 26 | gumballMachine.setState(gumballMachine.getWinnerState()); 27 | } else { 28 | gumballMachine.setState(gumballMachine.getSoldState()); 29 | } 30 | } 31 | 32 | public void dispense() { 33 | System.out.println("No gumball dispensed"); 34 | } 35 | 36 | public String toString() { 37 | return "waiting for turn of crank"; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstatewinner/NoQuarterState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstatewinner; 2 | 3 | public class NoQuarterState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public NoQuarterState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You inserted a quarter"); 12 | gumballMachine.setState(gumballMachine.getHasQuarterState()); 13 | } 14 | 15 | public void ejectQuarter() { 16 | System.out.println("You haven't inserted a quarter"); 17 | } 18 | 19 | public void turnCrank() { 20 | System.out.println("You turned, but there's no quarter"); 21 | } 22 | 23 | public void dispense() { 24 | System.out.println("You need to pay first"); 25 | } 26 | 27 | public String toString() { 28 | return "waiting for quarter"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstatewinner/SoldOutState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstatewinner; 2 | 3 | public class SoldOutState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public SoldOutState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("You can't insert a quarter, the machine is sold out"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("You can't eject, you haven't inserted a quarter yet"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("You turned, but there are no gumballs"); 20 | } 21 | 22 | public void dispense() { 23 | System.out.println("No gumball dispensed"); 24 | } 25 | 26 | public String toString() { 27 | return "sold out"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstatewinner/SoldState.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstatewinner; 2 | 3 | public class SoldState implements State { 4 | GumballMachine gumballMachine; 5 | 6 | public SoldState(GumballMachine gumballMachine) { 7 | this.gumballMachine = gumballMachine; 8 | } 9 | 10 | public void insertQuarter() { 11 | System.out.println("Please wait, we're already giving you a gumball"); 12 | } 13 | 14 | public void ejectQuarter() { 15 | System.out.println("Sorry, you already turned the crank"); 16 | } 17 | 18 | public void turnCrank() { 19 | System.out.println("Turning twice doesn't get you another gumball!"); 20 | } 21 | 22 | public void dispense() { 23 | gumballMachine.releaseBall(); 24 | if (gumballMachine.getCount() > 0) { 25 | gumballMachine.setState(gumballMachine.getNoQuarterState()); 26 | } else { 27 | System.out.println("Oops, out of gumballs!"); 28 | gumballMachine.setState(gumballMachine.getSoldOutState()); 29 | } 30 | } 31 | 32 | public String toString() { 33 | return "dispensing a gumball"; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/headfirst/state/gumballstatewinner/State.java: -------------------------------------------------------------------------------- 1 | package headfirst.state.gumballstatewinner; 2 | 3 | public interface State { 4 | 5 | public void insertQuarter(); 6 | public void ejectQuarter(); 7 | public void turnCrank(); 8 | public void dispense(); 9 | } 10 | -------------------------------------------------------------------------------- /src/headfirst/strategy/DecoyDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class DecoyDuck extends Duck { 4 | public DecoyDuck() { 5 | setFlyBehavior(new FlyNoWay()); 6 | setQuackBehavior(new MuteQuack()); 7 | } 8 | public void display() { 9 | System.out.println("I'm a duck Decoy"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/headfirst/strategy/Duck.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public abstract class Duck { 4 | FlyBehavior flyBehavior; 5 | QuackBehavior quackBehavior; 6 | 7 | public Duck() { 8 | } 9 | 10 | public void setFlyBehavior (FlyBehavior fb) { 11 | flyBehavior = fb; 12 | } 13 | 14 | public void setQuackBehavior(QuackBehavior qb) { 15 | quackBehavior = qb; 16 | } 17 | 18 | abstract void display(); 19 | 20 | public void performFly() { 21 | flyBehavior.fly(); 22 | } 23 | 24 | public void performQuack() { 25 | quackBehavior.quack(); 26 | } 27 | 28 | public void swim() { 29 | System.out.println("All ducks float, even decoys!"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/headfirst/strategy/FakeQuack.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class FakeQuack implements QuackBehavior { 4 | public void quack() { 5 | System.out.println("Qwak"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/strategy/FlyBehavior.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public interface FlyBehavior { 4 | public void fly(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/strategy/FlyNoWay.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class FlyNoWay implements FlyBehavior { 4 | public void fly() { 5 | System.out.println("I can't fly"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/strategy/FlyRocketPowered.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class FlyRocketPowered implements FlyBehavior { 4 | public void fly() { 5 | System.out.println("I'm flying with a rocket"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/strategy/FlyWithWings.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class FlyWithWings implements FlyBehavior { 4 | public void fly() { 5 | System.out.println("I'm flying!!"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/strategy/MallardDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class MallardDuck extends Duck { 4 | 5 | public MallardDuck() { 6 | 7 | quackBehavior = new Quack(); 8 | flyBehavior = new FlyWithWings(); 9 | 10 | 11 | } 12 | 13 | public void display() { 14 | System.out.println("I'm a real Mallard duck"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/headfirst/strategy/MiniDuckSimulator.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class MiniDuckSimulator { 4 | 5 | public static void main(String[] args) { 6 | 7 | MallardDuck mallard = new MallardDuck(); 8 | RubberDuck rubberDuckie = new RubberDuck(); 9 | DecoyDuck decoy = new DecoyDuck(); 10 | 11 | ModelDuck model = new ModelDuck(); 12 | 13 | mallard.performQuack(); 14 | rubberDuckie.performQuack(); 15 | decoy.performQuack(); 16 | 17 | model.performFly(); 18 | model.setFlyBehavior(new FlyRocketPowered()); 19 | model.performFly(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/headfirst/strategy/MiniDuckSimulator1.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class MiniDuckSimulator1 { 4 | 5 | public static void main(String[] args) { 6 | 7 | Duck mallard = new MallardDuck(); 8 | mallard.performQuack(); 9 | mallard.performFly(); 10 | 11 | Duck model = new ModelDuck(); 12 | model.performFly(); 13 | model.setFlyBehavior(new FlyRocketPowered()); 14 | model.performFly(); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/headfirst/strategy/ModelDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class ModelDuck extends Duck { 4 | public ModelDuck() { 5 | flyBehavior = new FlyNoWay(); 6 | quackBehavior = new Quack(); 7 | } 8 | 9 | public void display() { 10 | System.out.println("I'm a model duck"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/headfirst/strategy/MuteQuack.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class MuteQuack implements QuackBehavior { 4 | public void quack() { 5 | System.out.println("<< Silence >>"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/strategy/Quack.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class Quack implements QuackBehavior { 4 | public void quack() { 5 | System.out.println("Quack"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/strategy/QuackBehavior.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public interface QuackBehavior { 4 | public void quack(); 5 | } 6 | -------------------------------------------------------------------------------- /src/headfirst/strategy/RedHeadDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class RedHeadDuck extends Duck { 4 | 5 | public RedHeadDuck() { 6 | flyBehavior = new FlyWithWings(); 7 | quackBehavior = new Quack(); 8 | } 9 | 10 | public void display() { 11 | System.out.println("I'm a real Red Headed duck"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/strategy/RubberDuck.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class RubberDuck extends Duck { 4 | 5 | public RubberDuck() { 6 | flyBehavior = new FlyNoWay(); 7 | quackBehavior = new Squeak(); 8 | } 9 | 10 | public void display() { 11 | System.out.println("I'm a rubber duckie"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/strategy/Squeak.java: -------------------------------------------------------------------------------- 1 | package headfirst.strategy; 2 | 3 | public class Squeak implements QuackBehavior { 4 | public void quack() { 5 | System.out.println("Squeak"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/applet/MyApplet.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.applet; 2 | 3 | import java.applet.Applet; 4 | import java.awt.Graphics; 5 | 6 | public class MyApplet extends Applet { 7 | String message; 8 | 9 | public void init() { 10 | message = "Hello World, I'm alive!"; 11 | repaint(); 12 | } 13 | 14 | public void start() { 15 | message = "Now I'm starting up..."; 16 | repaint(); 17 | } 18 | 19 | public void stop() { 20 | message = "Oh, now I'm being stopped..."; 21 | repaint(); 22 | } 23 | 24 | public void destroy() { 25 | message = "Goodbye, cruel world"; 26 | repaint(); 27 | } 28 | 29 | public void paint(Graphics g) { 30 | g.drawString(message, 5, 15); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/BeverageTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | public class BeverageTestDrive { 4 | public static void main(String[] args) { 5 | 6 | Tea tea = new Tea(); 7 | Coffee coffee = new Coffee(); 8 | 9 | System.out.println("\nMaking tea..."); 10 | tea.prepareRecipe(); 11 | 12 | System.out.println("\nMaking coffee..."); 13 | coffee.prepareRecipe(); 14 | 15 | 16 | TeaWithHook teaHook = new TeaWithHook(); 17 | CoffeeWithHook coffeeHook = new CoffeeWithHook(); 18 | 19 | System.out.println("\nMaking tea..."); 20 | teaHook.prepareRecipe(); 21 | 22 | System.out.println("\nMaking coffee..."); 23 | coffeeHook.prepareRecipe(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/CaffeineBeverage.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | public abstract class CaffeineBeverage { 4 | 5 | final void prepareRecipe() { 6 | boilWater(); 7 | brew(); 8 | pourInCup(); 9 | addCondiments(); 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 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/CaffeineBeverageWithHook.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | public abstract class CaffeineBeverageWithHook { 4 | 5 | void prepareRecipe() { 6 | boilWater(); 7 | brew(); 8 | pourInCup(); 9 | if (customerWantsCondiments()) { 10 | addCondiments(); 11 | } 12 | } 13 | 14 | abstract void brew(); 15 | 16 | abstract void addCondiments(); 17 | 18 | void boilWater() { 19 | System.out.println("Boiling water"); 20 | } 21 | 22 | void pourInCup() { 23 | System.out.println("Pouring into cup"); 24 | } 25 | 26 | boolean customerWantsCondiments() { 27 | return true; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/Coffee.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | public class Coffee extends CaffeineBeverage { 4 | public void brew() { 5 | System.out.println("Dripping Coffee through filter"); 6 | } 7 | public void addCondiments() { 8 | System.out.println("Adding Sugar and Milk"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/CoffeeWithHook.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | import java.io.*; 4 | 5 | public class CoffeeWithHook extends CaffeineBeverageWithHook { 6 | 7 | public void brew() { 8 | System.out.println("Dripping Coffee through filter"); 9 | } 10 | 11 | public void addCondiments() { 12 | System.out.println("Adding Sugar and Milk"); 13 | } 14 | 15 | public boolean customerWantsCondiments() { 16 | 17 | String answer = getUserInput(); 18 | 19 | if (answer.toLowerCase().startsWith("y")) { 20 | return true; 21 | } else { 22 | return false; 23 | } 24 | } 25 | 26 | private String getUserInput() { 27 | String answer = null; 28 | 29 | System.out.print("Would you like milk and sugar with your coffee (y/n)? "); 30 | 31 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 32 | try { 33 | answer = in.readLine(); 34 | } catch (IOException ioe) { 35 | System.err.println("IO error trying to read your answer"); 36 | } 37 | if (answer == null) { 38 | return "no"; 39 | } 40 | return answer; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/Tea.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | public class Tea extends CaffeineBeverage { 4 | public void brew() { 5 | System.out.println("Steeping the tea"); 6 | } 7 | public void addCondiments() { 8 | System.out.println("Adding Lemon"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/barista/TeaWithHook.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.barista; 2 | 3 | import java.io.*; 4 | 5 | public class TeaWithHook extends CaffeineBeverageWithHook { 6 | 7 | public void brew() { 8 | System.out.println("Steeping the tea"); 9 | } 10 | 11 | public void addCondiments() { 12 | System.out.println("Adding Lemon"); 13 | } 14 | 15 | public boolean customerWantsCondiments() { 16 | 17 | String answer = getUserInput(); 18 | 19 | if (answer.toLowerCase().startsWith("y")) { 20 | return true; 21 | } else { 22 | return false; 23 | } 24 | } 25 | 26 | private String getUserInput() { 27 | // get the user's response 28 | String answer = null; 29 | 30 | System.out.print("Would you like lemon with your tea (y/n)? "); 31 | 32 | BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 33 | try { 34 | answer = in.readLine(); 35 | } catch (IOException ioe) { 36 | System.err.println("IO error trying to read your answer"); 37 | } 38 | if (answer == null) { 39 | return "no"; 40 | } 41 | return answer; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/frame/MyFrame.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.frame; 2 | 3 | import java.awt.*; 4 | import javax.swing.*; 5 | 6 | public class MyFrame extends JFrame { 7 | 8 | public MyFrame(String title) { 9 | super(title); 10 | this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11 | 12 | this.setSize(300,300); 13 | this.setVisible(true); 14 | } 15 | 16 | public void paint(Graphics graphics) { 17 | super.paint(graphics); 18 | String msg = "I rule!!"; 19 | graphics.drawString(msg, 100, 100); 20 | } 21 | 22 | public static void main(String[] args) { 23 | MyFrame myFrame = new MyFrame("Head First Design Patterns"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/simplebarista/Barista.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.simplebarista; 2 | 3 | public class Barista { 4 | 5 | public static void main(String[] args) { 6 | Tea tea = new Tea(); 7 | Coffee coffee = new Coffee(); 8 | System.out.println("Making tea..."); 9 | tea.prepareRecipe(); 10 | System.out.println("Making coffee..."); 11 | coffee.prepareRecipe(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/simplebarista/Coffee.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.simplebarista; 2 | 3 | public class Coffee { 4 | 5 | void prepareRecipe() { 6 | boilWater(); 7 | brewCoffeeGrinds(); 8 | pourInCup(); 9 | addSugarAndMilk(); 10 | } 11 | 12 | public void boilWater() { 13 | System.out.println("Boiling water"); 14 | } 15 | 16 | public void brewCoffeeGrinds() { 17 | System.out.println("Dripping Coffee through filter"); 18 | } 19 | 20 | public void pourInCup() { 21 | System.out.println("Pouring into cup"); 22 | } 23 | 24 | public void addSugarAndMilk() { 25 | System.out.println("Adding Sugar and Milk"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/simplebarista/Tea.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.simplebarista; 2 | 3 | public class Tea { 4 | 5 | void prepareRecipe() { 6 | boilWater(); 7 | steepTeaBag(); 8 | pourInCup(); 9 | addLemon(); 10 | } 11 | 12 | public void boilWater() { 13 | System.out.println("Boiling water"); 14 | } 15 | 16 | public void steepTeaBag() { 17 | System.out.println("Steeping the tea"); 18 | } 19 | 20 | public void addLemon() { 21 | System.out.println("Adding Lemon"); 22 | } 23 | 24 | public void pourInCup() { 25 | System.out.println("Pouring into cup"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/sort/Duck.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.sort; 2 | 3 | public class Duck implements Comparable { 4 | String name; 5 | int weight; 6 | 7 | public Duck(String name, int weight) { 8 | this.name = name; 9 | this.weight = weight; 10 | } 11 | 12 | public String toString() { 13 | return name + " weighs " + weight; 14 | } 15 | 16 | 17 | 18 | public int compareTo(Object object) { 19 | 20 | Duck otherDuck = (Duck)object; 21 | 22 | if (this.weight < otherDuck.weight) { 23 | return -1; 24 | } else if (this.weight == otherDuck.weight) { 25 | return 0; 26 | } else { // this.weight > otherDuck.weight 27 | return 1; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/headfirst/templatemethod/sort/DuckSortTestDrive.java: -------------------------------------------------------------------------------- 1 | package headfirst.templatemethod.sort; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | 6 | public class DuckSortTestDrive { 7 | 8 | public static void main(String[] args) { 9 | Duck[] ducks = { 10 | new Duck("Daffy", 8), 11 | new Duck("Dewey", 2), 12 | new Duck("Howard", 7), 13 | new Duck("Louie", 2), 14 | new Duck("Donald", 10), 15 | new Duck("Huey", 2) 16 | }; 17 | 18 | System.out.println("Before sorting:"); 19 | display(ducks); 20 | 21 | Arrays.sort(ducks); 22 | 23 | System.out.println("\nAfter sorting:"); 24 | display(ducks); 25 | } 26 | 27 | public static void display(Duck[] ducks) { 28 | for (int i = 0; i < ducks.length; i++) { 29 | System.out.println(ducks[i]); 30 | } 31 | } 32 | } 33 | --------------------------------------------------------------------------------