├── AbstractFactory.java ├── AdapterPattern.java ├── BridgePattern.java ├── BuilderPattern.java ├── CompositDesignPattern.java ├── DecoratorDesignPattern.java ├── FacadePattern.java ├── IteratorPattern.java ├── MediatorDesignPattern.java ├── MementoPattern.java ├── ProxyDesignPattern.java ├── README.md └── VisitorDesignPattern.java /AbstractFactory.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class AbstractFactory { 4 | 5 | 6 | 7 | public static void main(String[] args) { 8 | 9 | HotDrinkFactory factory = new CoffeeFactoryImp(); 10 | factory.prepare(10).consume(); 11 | factory = new TeaFactoryImp(); 12 | factory.prepare(5).consume(); 13 | } 14 | 15 | } 16 | 17 | interface HotDrink{ 18 | void consume(); 19 | } 20 | class Tea implements HotDrink{ 21 | 22 | @Override 23 | public void consume() { 24 | System.out.println("preparing tea"); 25 | } 26 | } 27 | 28 | class Coffee implements HotDrink{ 29 | 30 | @Override 31 | public void consume() { 32 | System.out.println("preparing coffee"); 33 | } 34 | } 35 | 36 | interface HotDrinkFactory{ 37 | 38 | HotDrink prepare(int amount); 39 | } 40 | 41 | 42 | class CoffeeFactoryImp implements HotDrinkFactory { 43 | 44 | @Override 45 | public HotDrink prepare(int amount) { 46 | return new Coffee(); 47 | 48 | } 49 | } 50 | 51 | class TeaFactoryImp implements HotDrinkFactory { 52 | 53 | @Override 54 | public HotDrink prepare(int amount) { 55 | return new Tea(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /AdapterPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class AdapterPattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | Voltage5w voltage5w = new VoltageAdapter(); 8 | System.out.println(voltage5w.volatge5w()); 9 | 10 | } 11 | 12 | } 13 | 14 | interface IVoltage220w{ 15 | int getVoltage220(); 16 | } 17 | 18 | 19 | class Voltage220WImp implements IVoltage220w{ 20 | 21 | @Override 22 | public int getVoltage220() { 23 | return 220; 24 | } 25 | 26 | } 27 | 28 | interface Voltage5w{ 29 | int volatge5w(); 30 | 31 | } 32 | 33 | class VoltageAdapter extends Voltage220WImp implements Voltage5w{ 34 | 35 | @Override 36 | public int volatge5w() { 37 | return getVoltage220()/44; 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /BridgePattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class BridgePattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | Gear gearManual = new ManualGear(); 8 | Gear gearAutomatic = new AutoMaticGear(); 9 | Vehicle vehicle = new Car(gearManual); 10 | Vehicle vehicleTruck = new Truck(gearAutomatic); 11 | vehicle.addGear(); 12 | vehicleTruck.addGear(); 13 | 14 | } 15 | } 16 | 17 | 18 | interface Gear { 19 | void handleGear(); 20 | } 21 | 22 | class ManualGear implements Gear{ 23 | 24 | @Override 25 | public void handleGear() { 26 | System.out.println("handle manyal gear"); 27 | } 28 | } 29 | 30 | 31 | class AutoMaticGear implements Gear { 32 | 33 | @Override 34 | public void handleGear() { 35 | System.out.println("handle automatic gear"); 36 | } 37 | 38 | } 39 | 40 | 41 | abstract class Vehicle{ 42 | 43 | Gear gear; 44 | Vehicle(Gear gear){ 45 | this.gear = gear; 46 | } 47 | abstract void addGear(); 48 | } 49 | 50 | class Car extends Vehicle{ 51 | 52 | Car(Gear gear){ 53 | super(gear); 54 | } 55 | 56 | @Override 57 | public void addGear() { 58 | gear.handleGear(); 59 | } 60 | } 61 | 62 | 63 | class Truck extends Vehicle{ 64 | 65 | Truck(Gear gear) { 66 | super(gear); 67 | } 68 | 69 | @Override 70 | public void addGear() { 71 | gear.handleGear(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /BuilderPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | 4 | public class BuilderPattern { 5 | 6 | public String name; 7 | 8 | // address 9 | public String streetAddress, postalCode, city; 10 | 11 | // work 12 | public String companyName, position; 13 | public long anualIncome; 14 | 15 | 16 | public static void main(String[] args) { 17 | PersonBuilder builder = new PersonBuilder(); 18 | BuilderPattern person = builder 19 | .withName("Tarun") 20 | .lives() 21 | .at("South west") 22 | .in("Delhi") 23 | .withPostalCode("110064") 24 | .works() 25 | .at("xyz") 26 | .position("senior software engineer") 27 | .annualIncome(1234567) 28 | .build(); 29 | 30 | System.out.println(person.toString()); 31 | 32 | 33 | } 34 | 35 | } 36 | 37 | 38 | 39 | class PersonBuilder { 40 | 41 | public BuilderPattern person = new BuilderPattern(); 42 | 43 | PersonBuilder withName(String name) { 44 | person.name=name; 45 | return this; 46 | } 47 | 48 | AddressBuilder lives() { 49 | return new AddressBuilder(person); 50 | } 51 | 52 | WorkBuilder works() { 53 | return new WorkBuilder(person); 54 | } 55 | 56 | BuilderPattern build() { 57 | return person; 58 | } 59 | 60 | } 61 | 62 | class AddressBuilder extends PersonBuilder { 63 | 64 | 65 | public AddressBuilder(BuilderPattern person) { 66 | this.person = person; 67 | } 68 | 69 | public AddressBuilder at(String address) { 70 | person.streetAddress = address; 71 | return this; 72 | } 73 | 74 | public AddressBuilder withPostalCode(String postalCode) { 75 | person.postalCode = postalCode; 76 | return this; 77 | } 78 | 79 | public AddressBuilder in(String city) { 80 | person.city = city; 81 | return this; 82 | } 83 | 84 | 85 | } 86 | 87 | class WorkBuilder extends PersonBuilder{ 88 | 89 | public WorkBuilder(BuilderPattern person) { 90 | this.person = person; 91 | } 92 | 93 | public WorkBuilder position(String position) { 94 | person.position = position; 95 | return this; 96 | } 97 | 98 | public WorkBuilder at(String companyName) { 99 | person.companyName = companyName; 100 | return this; 101 | } 102 | WorkBuilder annualIncome(long income) { 103 | person.anualIncome = income; 104 | return this; 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /CompositDesignPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class CompositDesignPattern { 6 | 7 | public static void main(String[] args) { 8 | 9 | File file1 = new Text(20); 10 | File file2 = new Text(30); 11 | 12 | System.out.println(file1.getSize()); 13 | System.out.println(file2.getSize()); 14 | 15 | Directory directory = new Directory(); 16 | Directory directory1 = new Directory(); 17 | directory1.addFile(new Text(50)); 18 | directory.addFile(file1,file2,directory1); 19 | System.out.println(directory.getSize()); 20 | } 21 | 22 | } 23 | 24 | 25 | interface File { 26 | String getFileType(); 27 | int getSize(); 28 | } 29 | 30 | 31 | class Text implements File { 32 | int size = 0; 33 | 34 | Text(int size){ 35 | this.size = size; 36 | } 37 | 38 | @Override 39 | public String getFileType() { 40 | return ".txt"; 41 | } 42 | 43 | @Override 44 | public int getSize() { 45 | return size; 46 | } 47 | 48 | } 49 | 50 | 51 | class Directory implements File { 52 | 53 | ArrayList files = new ArrayList(); 54 | 55 | void addFile(File... files) { 56 | for(File file:files) { 57 | this.files.add(file); 58 | } 59 | } 60 | 61 | 62 | @Override 63 | public String getFileType() { 64 | return ".dir"; 65 | } 66 | 67 | @Override 68 | public int getSize() { 69 | int size =0 ; 70 | 71 | for(File file : files) { 72 | size += file.getSize(); 73 | } 74 | 75 | return size; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /DecoratorDesignPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class DecoratorDesignPattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | BasePizza pizza = new MargrettaPizza(); 8 | System.out.println("MargrettaPizza price: "+pizza.getPrice()); 9 | BasePizza extraCheese = new ExtraCheeseWithPizza(pizza); 10 | System.out.println("MargrettaPizza extra cheese price: "+extraCheese.getPrice()); 11 | BasePizza doubleCheese = new ExtraCheeseWithPizza(extraCheese); 12 | System.out.println("MargrettaPizza double cheese price: "+doubleCheese.getPrice()); 13 | } 14 | } 15 | 16 | 17 | 18 | interface BasePizza { 19 | int getPrice(); 20 | } 21 | 22 | class MargrettaPizza implements BasePizza{ 23 | 24 | @Override 25 | public int getPrice() { 26 | // TODO Auto-generated method stub 27 | return 60; 28 | } 29 | 30 | } 31 | 32 | class VegPizza implements BasePizza{ 33 | 34 | @Override 35 | public int getPrice() { 36 | // TODO Auto-generated method stub 37 | return 80; 38 | } 39 | 40 | } 41 | 42 | class VegLoadedPizza implements BasePizza{ 43 | 44 | @Override 45 | public int getPrice() { 46 | // TODO Auto-generated method stub 47 | return 100; 48 | } 49 | } 50 | 51 | 52 | class ExtraCheeseWithPizza implements BasePizza{ 53 | 54 | BasePizza pizza; 55 | 56 | public ExtraCheeseWithPizza(BasePizza pizza) { 57 | this.pizza = pizza; 58 | } 59 | 60 | @Override 61 | public int getPrice() { 62 | return pizza.getPrice() + 20; 63 | } 64 | 65 | } 66 | 67 | -------------------------------------------------------------------------------- /FacadePattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class FacadePattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | Kitchen kitchen = new KitchenImp(); 8 | Waiter waiter = new WaiterImp(); 9 | 10 | Facade facade = new FacadeImp(kitchen, waiter); 11 | facade.serveCustomer(); 12 | 13 | } 14 | 15 | } 16 | 17 | 18 | interface Waiter{ 19 | void writeOrder(); 20 | void giveToKitchen(); 21 | void serveOrder(); 22 | } 23 | 24 | interface Kitchen{ 25 | void prepareOrder(); 26 | void callWaiter(); 27 | void washDishes(); 28 | } 29 | 30 | 31 | class WaiterImp implements Waiter { 32 | 33 | @Override 34 | public void writeOrder() { 35 | System.out.println("writing order"); 36 | } 37 | 38 | @Override 39 | public void giveToKitchen() { 40 | System.out.println("order give to kitchen"); 41 | } 42 | 43 | @Override 44 | public void serveOrder() { 45 | System.out.println("serve order to customer"); 46 | 47 | } 48 | 49 | } 50 | 51 | 52 | 53 | class KitchenImp implements Kitchen { 54 | 55 | @Override 56 | public void prepareOrder() { 57 | System.out.println("preparing order"); 58 | } 59 | 60 | @Override 61 | public void callWaiter() { 62 | System.out.println("calling waiter for serving"); 63 | } 64 | 65 | @Override 66 | public void washDishes() { 67 | System.out.println("washing dishes"); 68 | } 69 | 70 | } 71 | 72 | 73 | interface Facade { 74 | void serveCustomer(); 75 | } 76 | 77 | 78 | class FacadeImp implements Facade { 79 | 80 | Kitchen kitchen; 81 | Waiter waiter; 82 | 83 | public FacadeImp(Kitchen kitchen, Waiter waiter) { 84 | this.kitchen= kitchen; 85 | this.waiter = waiter; 86 | } 87 | 88 | @Override 89 | public void serveCustomer() { 90 | waiter.writeOrder(); 91 | waiter.giveToKitchen(); 92 | kitchen.prepareOrder(); 93 | kitchen.callWaiter(); 94 | waiter.serveOrder(); 95 | kitchen.washDishes(); 96 | } 97 | 98 | } 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /IteratorPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class IteratorPattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | Iterator iterate = new NameRepository().getIterator(); 8 | while(iterate.hasNext()) { 9 | System.out.println(iterate.next()+""); 10 | } 11 | 12 | } 13 | } 14 | 15 | 16 | interface Iterator { 17 | boolean hasNext(); 18 | Object next(); 19 | } 20 | 21 | interface Container { 22 | Iterator getIterator(); 23 | } 24 | 25 | 26 | class NameRepository implements Container { 27 | 28 | int index = 0; 29 | String name[] = {"name1","name2","name3","name4"}; 30 | 31 | 32 | class NameIterator implements Iterator{ 33 | 34 | @Override 35 | public boolean hasNext() { 36 | if(index users=new ArrayList(); 31 | 32 | void addUsers(User user){ 33 | users.add(user); 34 | } 35 | 36 | @Override 37 | public void sendMessage(User user,String msg) { 38 | 39 | for(User user1: users) { 40 | if(user1!=user) { 41 | user1.receiveMessage(user,msg); 42 | } 43 | } 44 | } 45 | 46 | @Override 47 | public void addUser(User user) { 48 | users.add(user); 49 | } 50 | 51 | } 52 | 53 | 54 | abstract class User { 55 | 56 | ChatMediator mediator; 57 | protected String name; 58 | 59 | public User(ChatMediator med, String name){ 60 | this.mediator=med; 61 | this.name=name; 62 | } 63 | 64 | abstract void sendMessage(String msg); 65 | abstract void receiveMessage(User user,String msg); 66 | } 67 | 68 | 69 | class UserImp extends User { 70 | 71 | public UserImp(ChatMediator med, String name) { 72 | super(med, name); 73 | } 74 | 75 | @Override 76 | void sendMessage(String message) { 77 | this.mediator.sendMessage(this,message); 78 | } 79 | 80 | @Override 81 | void receiveMessage(User user, String msg) { 82 | System.out.println(user.name +": "+msg+" to "+this.name); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /MementoPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class MementoPattern { 7 | 8 | public static void main(String[] args) { 9 | 10 | CareTaker careTaker = new CareTaker(); 11 | FileUtil filetutil1 = new FileUtil("name1","content1"); 12 | careTaker.add(filetutil1.save()); 13 | FileUtil filetutil2 = new FileUtil("name2","content2"); 14 | careTaker.add(filetutil2.save()); 15 | 16 | System.out.println("content: "+careTaker.undoLast().content +" filaname: " + careTaker.undoLast().fileName); 17 | 18 | } 19 | 20 | } 21 | 22 | class CareTaker { 23 | 24 | List list = new ArrayList(); 25 | 26 | void add(Memento memento) { 27 | this.list.add(memento); 28 | } 29 | 30 | FileUtil undoLast() { 31 | if(list.size()>=2) { 32 | return list.get(list.size()-2).fileUtil; 33 | } 34 | return list.get(list.size()-1).fileUtil; 35 | } 36 | 37 | } 38 | 39 | class FileUtil { 40 | 41 | String fileName; 42 | String content; 43 | 44 | FileUtil(String fileName,String content){ 45 | this.fileName=fileName; 46 | this.content=content; 47 | } 48 | 49 | public String getFileName() { 50 | return fileName; 51 | } 52 | 53 | public void setFileName(String fileName) { 54 | this.fileName = fileName; 55 | } 56 | 57 | public String getContent() { 58 | return content; 59 | } 60 | 61 | public void setContent(String content) { 62 | this.content = content; 63 | } 64 | 65 | Memento save() { 66 | System.out.println("saving: "+"filename: "+fileName +" content: "+content); 67 | return new Memento(this); 68 | } 69 | 70 | } 71 | 72 | class Memento { 73 | FileUtil fileUtil; 74 | 75 | public Memento(FileUtil fileUtil) { 76 | this.fileUtil = fileUtil; 77 | } 78 | 79 | public FileUtil getFileUtil() { 80 | return fileUtil; 81 | } 82 | 83 | public void setFileUtil(FileUtil fileUtil) { 84 | this.fileUtil = fileUtil; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /ProxyDesignPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class ProxyDesignPattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | News news = new ProxyNews("india tv"); 8 | news.loadNews(); 9 | news = new ProxyNews("xyzs"); 10 | news.loadNews(); 11 | 12 | } 13 | 14 | } 15 | 16 | interface News { 17 | void loadNews(); 18 | } 19 | 20 | class RealNews implements News { 21 | 22 | String url; 23 | 24 | public RealNews(String url) { 25 | this.url = url; 26 | } 27 | 28 | @Override 29 | public void loadNews() { 30 | System.out.println("loading news: "+url); 31 | } 32 | 33 | } 34 | 35 | 36 | class ProxyNews implements News { 37 | 38 | String newsUrl; 39 | News realNews; 40 | 41 | public ProxyNews(String newsUrl) { 42 | this.newsUrl = newsUrl; 43 | } 44 | 45 | 46 | @Override 47 | public void loadNews() { 48 | //if this type of news url comes we'll navigate it to different url 49 | if(newsUrl.contains("xyz")) { 50 | newsUrl = "abc"; 51 | } 52 | 53 | if(realNews==null) { 54 | realNews = new RealNews(newsUrl); 55 | } 56 | realNews.loadNews(); 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Design Patterns 2 | ## Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.
3 | ### I've tried my best to pick easiest examples, hopefully it'll help you to solve complex design problems. 4 | Abstract Factory Pattern
5 | Singleton Pattern
6 | Builder Pattern
7 | Adapter Pattern
8 | Bridge Pattern
9 | Iterator Pattern
10 | Mediator Pattern
11 | Memento Pattern
12 | Composite Pattern
13 | Decorator Pattern
14 | Facade Pattern
15 | Proxy Pattern
16 | Visitor Pattern
17 | 18 | 19 | -------------------------------------------------------------------------------- /VisitorDesignPattern.java: -------------------------------------------------------------------------------- 1 | package oopsdesign; 2 | 3 | public class VisitorDesignPattern { 4 | 5 | public static void main(String[] args) { 6 | 7 | ItemElement[] items = new ItemElement[] {new Book(10,"1234"),new Fruit(20,5,"Apple")}; 8 | int price = 0; 9 | ShoppingCartVisitor visititem = new ShoppingCartVisitorImpl(); 10 | for(ItemElement item: items) { 11 | price = price+ item.accept(visititem); 12 | } 13 | System.out.println("price: "+price); 14 | } 15 | } 16 | 17 | 18 | interface ItemElement 19 | { 20 | public int accept(ShoppingCartVisitor visitor); 21 | } 22 | 23 | class Book implements ItemElement 24 | { 25 | private int price; 26 | private String isbnNumber; 27 | 28 | public Book(int cost, String isbn) 29 | { 30 | this.price=cost; 31 | this.isbnNumber=isbn; 32 | } 33 | 34 | public int getPrice() 35 | { 36 | return price; 37 | } 38 | 39 | public String getIsbnNumber() 40 | { 41 | return isbnNumber; 42 | } 43 | 44 | @Override 45 | public int accept(ShoppingCartVisitor visitor) 46 | { 47 | return visitor.visit(this); 48 | } 49 | 50 | } 51 | 52 | class Fruit implements ItemElement 53 | { 54 | private int pricePerKg; 55 | private int weight; 56 | private String name; 57 | 58 | public Fruit(int priceKg, int wt, String nm) 59 | { 60 | this.pricePerKg=priceKg; 61 | this.weight=wt; 62 | this.name = nm; 63 | } 64 | 65 | public int getPricePerKg() 66 | { 67 | return pricePerKg; 68 | } 69 | 70 | public int getWeight() 71 | { 72 | return weight; 73 | } 74 | 75 | public String getName() 76 | { 77 | return this.name; 78 | } 79 | 80 | @Override 81 | public int accept(ShoppingCartVisitor visitor) 82 | { 83 | return visitor.visit(this); 84 | } 85 | 86 | } 87 | 88 | interface ShoppingCartVisitor 89 | { 90 | 91 | int visit(Book book); 92 | int visit(Fruit fruit); 93 | } 94 | 95 | class ShoppingCartVisitorImpl implements ShoppingCartVisitor 96 | { 97 | 98 | @Override 99 | public int visit(Book book) 100 | { 101 | int cost=0; 102 | //apply 5$ discount if book price is greater than 50 103 | if(book.getPrice() > 50) 104 | { 105 | cost = book.getPrice()-5; 106 | } 107 | else 108 | cost = book.getPrice(); 109 | 110 | System.out.println("Book ISBN::"+book.getIsbnNumber() + " cost ="+cost); 111 | return cost; 112 | } 113 | 114 | @Override 115 | public int visit(Fruit fruit) 116 | { 117 | int cost = fruit.getPricePerKg()*fruit.getWeight(); 118 | System.out.println(fruit.getName() + " cost = "+cost); 119 | return cost; 120 | } 121 | 122 | } 123 | 124 | class ShoppingCartClient 125 | { 126 | 127 | public static void main(String[] args) 128 | { 129 | ItemElement[] items = new ItemElement[]{new Book(20, "1234"), 130 | new Book(100, "5678"), new Fruit(10, 2, "Banana"), 131 | new Fruit(5, 5, "Apple")}; 132 | 133 | int total = calculatePrice(items); 134 | System.out.println("Total Cost = "+total); 135 | } 136 | 137 | private static int calculatePrice(ItemElement[] items) 138 | { 139 | ShoppingCartVisitor visitor = new ShoppingCartVisitorImpl(); 140 | int sum=0; 141 | for(ItemElement item : items) 142 | { 143 | sum = sum + item.accept(visitor); 144 | } 145 | return sum; 146 | } 147 | 148 | } --------------------------------------------------------------------------------