Video tutorial to demonstrate how to implement Decorator Design Pattern in Java.
Click here to download source code
Everything you want to know about Java.
package com.hubberspot.designpattern.behavioral.observer; public interface Subject { public void addObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObservers(); }
package com.hubberspot.designpattern.behavioral.observer; public interface Observer { public void update(int temperature); }
package com.hubberspot.designpattern.behavioral.observer; import java.util.ArrayList; import java.util.List; public class WeatherBroadcast implements Subject { private List< Observer > listOfObservers; private int temperature; public WeatherBroadcast() { listOfObservers = new ArrayList< Observer >(); } @Override public void addObserver(Observer observer) { listOfObservers.add(observer); } @Override public void removeObserver(Observer observer) { listOfObservers.remove(observer); } @Override public void notifyObservers() { for(Observer observer : listOfObservers) { observer.update(temperature); } } public void temperatureChanged(int newTemperature) { temperature = newTemperature; notifyObservers(); } }
package com.hubberspot.designpattern.behavioral.observer; public class NewsPaperAgency implements Observer { @Override public void update(int temperature) { System.out.println("News Paper Agencies gets current temperature as: " + temperature + " degrees"); } }
package com.hubberspot.designpattern.behavioral.observer; public class NewsChannel implements Observer { @Override public void update(int temperature) { System.out.println("News Channel gets current temperature as: " + temperature + " degrees"); } }
package com.hubberspot.designpattern.behavioral.observer; public class WeatherInfoWebsite implements Observer { @Override public void update(int temperature) { System.out.println("Weather Info Websites gets current temperature as: " + temperature + " degrees"); } }
package com.hubberspot.designpattern.behavioral.observer; public class ObserverDesignPatternTest { public static void main(String[] args) throws InterruptedException { WeatherBroadcast weatherBroadcast = new WeatherBroadcast(); Observer newsPaperAgency = new NewsPaperAgency(); Observer newsChannel = new NewsChannel(); Observer weatherInfoWebsite = new WeatherInfoWebsite(); weatherBroadcast.addObserver(newsPaperAgency); weatherBroadcast.addObserver(newsChannel); weatherBroadcast.addObserver(weatherInfoWebsite); weatherBroadcast.temperatureChanged(30); System.out.println("\nAfter 2 minutes temperature changes to 33 degrees...\n"); Thread.sleep(120000); weatherBroadcast.temperatureChanged(33); } }
package com.hubberspot.designpattern.structural.decorator; public class Pizza { public Pizza() { } public String description(){ return "Pizza"; } }
package com.hubberspot.designpattern.structural.decorator; public abstract class PizzaToppings extends Pizza { public abstract String description(); }
package com.hubberspot.designpattern.structural.decorator; public class ChickenMasala extends PizzaToppings { private Pizza pizza; public ChickenMasala(Pizza pizza) { this.pizza = pizza; } @Override public String description() { return pizza.description() + " with chicken masala, "; } }
package com.hubberspot.designpattern.structural.decorator; public class Onion extends PizzaToppings { private Pizza pizza; public Onion(Pizza pizza) { this.pizza = pizza; } @Override public String description() { return pizza.description() + "onions, "; } }
package com.hubberspot.designpattern.structural.decorator; public class MozzarellaCheese extends PizzaToppings { private Pizza pizza; public MozzarellaCheese(Pizza pizza) { this.pizza = pizza; } @Override public String description() { return pizza.description() + "and mozzarella cheese."; } }
package com.hubberspot.designpattern.structural.decorator; public class TestDecorator { public static void main(String[] args) { Pizza pizza = new Pizza(); pizza = new ChickenMasala(pizza); pizza = new Onion(pizza); pizza = new MozzarellaCheese(pizza); System.out.println("You're getting " + pizza.description()); } }
package com.hubberspot.designpattern.behavioral.iterator; public class Song { private String songName; private String singer; public Song(String songName, String singer) { super(); this.songName = songName; this.singer = singer; } public String getSongName() { return songName; } public String getSinger() { return singer; } }
package com.hubberspot.designpattern.behavioral.iterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class SongCollection { private List< Song > songList = new ArrayList< Song >(); public void addSong(Song song) { songList.add(song); } public Iterator< Song > getSongIterator() { return new SongIterator(); } private class SongIterator implements Iterator< Song > { int currentSongIndex = 0; @Override public boolean hasNext() { if (currentSongIndex >= songList.size()) { return false; } else { return true; } } @Override public Song next() { return songList.get(currentSongIndex++); } @Override public void remove() { songList.remove(--currentSongIndex); } } }
package com.hubberspot.designpattern.behavioral.iterator; import java.util.Iterator; public class SongIterationDemo { public static void main(String[] args) { Song s1 = new Song("Rock You !!!" , "Eric Martin"); Song s2 = new Song("Someone Gone !!!" , "Neuone Derek"); Song s3 = new Song("Remember Me !!!" , "Justin Diebler"); SongCollection songCollection = new SongCollection(); songCollection.addSong(s1); songCollection.addSong(s2); songCollection.addSong(s3); System.out.println("Displaying Song Info : \n"); Iterator< Song > songIterator = songCollection.getSongIterator(); while(songIterator.hasNext()) { Song song = songIterator.next(); System.out.println("Song Name : " + song.getSongName()); System.out.println("Song Singer : " + song.getSinger()); System.out.println(); } System.out.println("Removing Song and Displaying :\n"); songIterator.remove(); songIterator = songCollection.getSongIterator(); while(songIterator.hasNext()) { Song song = songIterator.next(); System.out.println("Song Name : " + song.getSongName()); System.out.println("Song Singer : " + song.getSinger()); System.out.println(); } } }
package com.hubberspot.designpattern.structural.composite; // This acts as a interface for every State(Leaf) and // Country(Composite) public abstract class GeographicalArea { // Name of the region private String areaName; public GeographicalArea(String areaName) { this.areaName = areaName; } public String getAreaName() { return areaName; } // Create methods which will throw UnsupportedOperationException public void addGeographicalArea(GeographicalArea geographicalArea) { throw new UnsupportedOperationException( "Invalid Operation. Not Supported"); } public GeographicalArea getGeographicalArea(int areaIndex) { throw new UnsupportedOperationException( "Invalid Operation. Not Supported"); } public long getPopulation() { throw new UnsupportedOperationException( "Invalid Operation. Not Supported"); } // Create a abstract method which will be implemented // by State and Country respectively public abstract void displayAreaInfo(); }
package com.hubberspot.designpattern.structural.composite; import java.util.ArrayList; import java.util.List; // It extends GeographicalArea and has a list of // objects containing the GeographicalArea such as // State in this case. public class Country extends GeographicalArea { List< GeographicalArea > listOfGeographicalArea = new ArrayList< GeographicalArea >(); public Country(String areaName) { super(areaName); } // adding states to country @Override public void addGeographicalArea(GeographicalArea geographicalArea) throws UnsupportedOperationException { listOfGeographicalArea.add(geographicalArea); } // getting states one by one based on index @Override public GeographicalArea getGeographicalArea(int areaIndex) throws UnsupportedOperationException { return listOfGeographicalArea.get(areaIndex); } // displaying the information for the country @Override public void displayAreaInfo() { System.out.println("Country name : " + getAreaName()); System.out.println("It has following info : "); long totalPopulation = 0; int index = 1; System.out.println("It has following states : "); for(GeographicalArea geographicalArea : listOfGeographicalArea) { System.out.println(index + " : "+ geographicalArea.getAreaName() ); System.out.println("It has population around : " + geographicalArea.getPopulation()); totalPopulation = totalPopulation + geographicalArea.getPopulation(); index++; } System.out.println("Total Population of "+ getAreaName()+ " is : " + totalPopulation); } }
package com.hubberspot.designpattern.structural.composite; //It extends GeographicalArea public class State extends GeographicalArea { // has a property called as population private long population; public long getPopulation() { return population; } public State(String areaName, long population) { super(areaName); this.population = population; } // displaying the information for the states @Override public void displayAreaInfo() { System.out.println("State name : " + getAreaName()); System.out.println("State population : " + getPopulation()); } }4. TestCompositePattern.java
package com.hubberspot.designpattern.structural.composite; public class TestCompositePattern { public static void main(String[] args) { // Create two countries such as India and USA GeographicalArea countryIndia = new Country("India"); GeographicalArea countryUSA = new Country("USA"); // Create two Indian States with name and population GeographicalArea stateMadhyaPradesh = new State("Madhya Pradesh", 10000000); GeographicalArea stateMaharashtra = new State("Maharashtra", 20000000); // Create two USA States with name and population GeographicalArea stateNewYork = new State("New York", 19570261); GeographicalArea stateWashington = new State("Washington", 6897012); // Add the Indian States to India countryIndia.addGeographicalArea(stateMadhyaPradesh); countryIndia.addGeographicalArea(stateMaharashtra); // Add the USA States to USA countryUSA.addGeographicalArea(stateNewYork); countryUSA.addGeographicalArea(stateWashington); // Display Info for country India countryIndia.displayAreaInfo(); System.out.println(); // Display Info for country USA countryUSA.displayAreaInfo(); } }
package com.hubberspot.designpattern.creational.builder; // 1. Create a Robot class which is to be build by // Builder Design Pattern. public class Robot { // 2. Robot has few properties/characteristics private String robotHead; private String robotTorso; private String robotArms; private String robotLegs; // 3. Create getters for each characteristics public String getRobotHead() { return robotHead; } public String getRobotTorso() { return robotTorso; } public String getRobotArms() { return robotArms; } public String getRobotLegs() { return robotLegs; } // 4. Create a static class which will build our // Robot public static class RobotBuilder { // 5. Provide it with properties with which it will // prepare the required Robot private String robotHead = ""; private String robotTorso = "" ; private String robotArms = ""; private String robotLegs = ""; public RobotBuilder() { } // 6. Create methods for each properties which Robot // requires to get in action. The client will pass // necessary values for the type of Robot they want. public RobotBuilder buildRobotHead(String robotHead) { this.robotHead = robotHead; return this; } public RobotBuilder buildRobotTorso(String robotTorso) { this.robotTorso = robotTorso; return this; } public RobotBuilder buildRobotArms(String robotArms) { this.robotArms = robotArms; return this; } public RobotBuilder buildRobotLegs(String robotLegs) { this.robotLegs = robotLegs; return this; } // 7. Final build method will return us back the required // Robot public Robot build() { return new Robot(this); } } // 8. Actual preparation of Robot by RobotBuilder private Robot(RobotBuilder robotBuilder) { robotHead = robotBuilder.robotHead; robotTorso = robotBuilder.robotTorso; robotArms = robotBuilder.robotArms; robotLegs = robotBuilder.robotLegs; } // 9. Creation of Iron Robot and Steel Robot by the // client. public static void main(String[] args) { System.out.println("Let's build a Iron Robot .... \n"); Robot ironRobot = new Robot.RobotBuilder() .buildRobotHead("Iron Head") .buildRobotTorso("Iron Torso") .buildRobotArms("Iron Arms") .buildRobotLegs("Iron Legs") .build(); System.out.println("Iron Robot is build with following specs : \n"); System.out.println("Robot Head : " + ironRobot.getRobotHead()); System.out.println("Robot Torso : " + ironRobot.getRobotTorso()); System.out.println("Robot Arms : " + ironRobot.getRobotArms()); System.out.println("Robot Legs : " + ironRobot.getRobotLegs()); System.out.println(); System.out.println("Let's build a Steel Robot .... \n"); Robot steelRobot = new Robot.RobotBuilder() .buildRobotHead("Steel Head") .buildRobotTorso("Steel Torso") .buildRobotArms("Steel Arms") .buildRobotLegs("Steel Legs") .build(); System.out.println("Steel Robot is build with following specs : \n"); System.out.println("Robot Head : " + steelRobot.getRobotHead()); System.out.println("Robot Torso : " + steelRobot.getRobotTorso()); System.out.println("Robot Arms : " + steelRobot.getRobotArms()); System.out.println("Robot Legs : " + steelRobot.getRobotLegs()); } }
package com.hubberspot.designpattern.creational.factorymethod; // 1. Create a Animal interface // having a method definition say eat public interface Animal { public void eat(); }
package com.hubberspot.designpattern.creational.factorymethod; // 2. Create a AnimalFactory which // will create instances of concrete // Animals public class AnimalFactory { // 3. Create a static getAnimal method which will // take package name + class name of class whose // instance is to be created. public static Animal getAnimal(String classInfo) { Animal animal = null; try { // 4. Class.forName(String) dynamically loads class // passed as a String to it. // 5. newInstance() method creates a concrete instance of // the class passed to Class.forName() as a String. animal = (Animal) Class.forName(classInfo).newInstance(); } catch (Exception e) { e.printStackTrace(); } // 6. We return the concrete instance. return animal; } }
package com.hubberspot.designpattern.creational.factorymethod; // 8. Concrete animal Dog for the Animal interface public class Dog implements Animal { @Override public void eat() { System.out.println("Dog eating .... "); } }
package com.hubberspot.designpattern.creational.factorymethod; // 7. Concrete animal Cat for the Animal interface public class Cat implements Animal { @Override public void eat() { System.out.println("Cat eating .... "); } }
package com.hubberspot.designpattern.creational.factorymethod; import com.hubberspot.designpattern.creational.factorymethod.Dog; public class TestFactoryDesignPattern { public static void main(String[] args) { // 9. Create a Dog object from the AnimalFactory by passing fully // qualified name for the concrete Dog class Dog dog = (Dog) AnimalFactory.getAnimal( "com.hubberspot.designpattern.creational.factorymethod.Dog" ); dog.eat(); // 10. Create a Cat object from the AnimalFactory by passing fully // qualified name for the concrete Cat class Cat cat = (Cat) AnimalFactory.getAnimal( "com.hubberspot.designpattern.creational.factorymethod.Cat" ); cat.eat(); } }