Design Patterns (Very simple examples)

Creational Design Pattern

public class Singleton {
//This is the variable where we will store instance
// This is static because we want only one instance
private static Singleton instance = null;//This is private class because we dont want someone to create //direct object of this classprivate Singleton() {
System.out.println("new object created of Singleton()");
}
//This is the factory method by which someone can access the //objectpublic static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Singleton obj1= Singleton.getInstance();
Class clazz = Class.forName("com.package.Singleton");
Constructor<Singleton> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);Singleton obj2= constructor.newInstance();System.out.println("HashCode of obj1: " + obj1.hashCode());
System.out.println("HashCode of obj2: " + obj2.hashCode());
Singleton obj1= Singleton.getInstance();
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("loction/save"));
outputStream.writeObject(singletone);
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("loction/save"));
Singleton obj2 = (Singleton) objectInputStream.readObject();System.out.println("HashCode of obj1: " + obj1.hashCode());
System.out.println("HashCode of obj2: " + obj2.hashCode());
Singleton obj1 = Singleton.getInstance();SingletonDesign obj2 = (Singleton) obj1.clone();
System.out.println("HashCode of obj1: " + obj1.hashCode());
System.out.println("HashCode of obj2: " + obj2.hashCode());
ExecutorService service = Executors.newFixedThreadPool(2);
service.submit(SingletonTest::useSingleton);
service.submit(SingletonTest::useSingleton);
service.shutdown();
static void useSingleton(){
Singleton singleton = Singleton.getInstance();
System.out.println("HashCode of obj: " + obj.hashCode());
}
public class Singleton {private static volatile Singleton mInstance;private Singleton() {
// To prevent reflection we need to do not null check
if (mInstance != null) {
throw new RuntimeException("Please use getInstance()");
}
System.out.println("Singleton Constructor");
}
public final static Singleton getInstance() {
// Make thread-safe Singleton by using Double Check Locking
if (mInstance == null) {
// 1- check
synchronized (Singleton.class) {
if (mInstance == null) {
// 2- check
mInstance
= new Singleton();
}
}
}
return mInstance;
}
//Prevent from Serialization
protected Object readResolve() throws ObjectStreamException {
//return the mInstance or throw the Exception
return mInstance;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// instead of super.clone() return the mInstance or throw the Exception
return mInstance;
}

}
public class Phone {    private String name;
private String brand;
private int prize;
private int ram;
public Phone(String name, String brand, int prize, int ram) {
this.name = name;
this.brand = brand;
this.prize = prize;
this.ram = ram;
}
@Override
public String toString() {
return "Phone{" +
"name='" + name + '\'' +
", brand='" + brand + '\'' +
", prize=" + prize +
", ram=" + ram +
'}';
}
}
public class PhoneBuilder {    private String name;
private String brand;
private int prize;
private int ram;
public String getName() {
return name;
}
public PhoneBuilder setName(String name) {
this.name = name;
return this;
}
public String getBrand() {
return brand;
}
public PhoneBuilder setBrand(String brand) {
this.brand = brand;
return this;
}
public int getPrize() {
return prize;
}
public PhoneBuilder setPrize(int prize) {
this.prize = prize;
return this;
}
public int getRam() {
return ram;
}
public PhoneBuilder setRam(int ram) {
this.ram = ram;
return this;
}
public Phone getPhone() {
return new Phone(name, brand, prize, ram);
}
}
public class PhoneConsumer {    public static void main(String[] args) {
Phone phone = new PhoneBuilder().setBrand("iPhone")
.setName("Apple").getPhone();
System.out.println(phone);
}
}
  1. Interface in which factory method will be there.
  2. Classes of what all types of shapes we want to create.
  3. A Factory will be responsible for creating the object of shape.
  4. The consumer will decide which type of shape is required.
public interface Shape {
void draw();
}
public class Circle implements Shape{    @Override
public void draw() {
System.out.println("Circle");
}
}
public class Rectangle implements Shape{    @Override
public void draw() {
System.out.println("Rectangle");
}
}
public class ShapeFactory {    public Shape getShape(String type) {
if (type.equalsIgnoreCase("rectangle")) {
return new Rectangle();
} else if (type.equalsIgnoreCase("circle")) {
return new Circle();
}
return null;
}
}
public class ShapeConsumer {    public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape s = shapeFactory.getShape("Circle");
s.draw();
}
}
public interface Color {
void fill();
}
public interface Shape {
void draw();
}
public abstract class AbstractFactory {
abstract Color getColor(String colorType);
abstract Shape getShape(String shapeType);
}
public class ColorFactory extends AbstractFactory {    @Override
public Color getColor(String colorType) {
if (colorType.equalsIgnoreCase("red")) {
return new Red();
} else if (colorType.equalsIgnoreCase("black")) {
return new Black();
}
return null;
}
@Override
public Shape getShape(String shapeType) {
return null;
}
}
public class ShapeFactory extends AbstractFactory {    @Override
public Color getColor(String colorType) {
return null;
}
@Override
public Shape getShape(String shapeType) {
if (shapeType.equalsIgnoreCase("ractangle")) {
return new Ractangle();
} else if (shapeType.equalsIgnoreCase("circle")) {
return new Circle();
}
return null;
}
}
public class FactoryProducer {    public static AbstractFactory getFactory(String type) {
if (type.equalsIgnoreCase("Shape")) {
return new ShapeFactory();
} else if (type.equalsIgnoreCase("Color")) {
return new ColorFactory();
}
return null;
}
}
public class ShapeAndColorConsumer {    public static void main(String[] args) {
AbstractFactory abstractFactory=FactoryProducer.getFactory("Color");
Color color=abstractFactory.getColor("red");
color.fill();
}
}

Structural Pattern

public interface Phone {
void modelName();
void modelPrice();
}
public class Iphone implements Phone {    @Override
public void modelName() {
System.out.println("Iphone");
}
@Override
public void modelPrice() {
System.out.println("6000");
}
}
public class Samsung implements Phone {    @Override
public void modelName() {
System.out.println("Samsung");
}
@Override
public void modelPrice() {
System.out.println("1000");
}
}
public class ShopKeeper {
Iphone iphone;
Samsung samsung;
public ShopKeeper() {
this.iphone = new Iphone();
this.samsung = new Samsung();
}
public void getIphoneDetail(){
iphone.modelName();
iphone.modelPrice();
}
public void getSamsungDetail(){
samsung.modelName();
samsung.modelPrice();
}
}
public class Customer {    public static void main(String[] args) {
ShopKeeper shopKeeper = new ShopKeeper();
shopKeeper.getIphoneDetail();
}
}
public interface Employee {
String getName();
int getId();
String getDepartment();
}
public class HRs implements Employee {

private String name;
private int id;
private String department;

public HRs(String name, int id, String department) {
this.name = name;
this.id = id;
this.department = department;
}

@Override
public String getName() {
return this.name;
}

@Override
public int getId() {
return this.id;
}

@Override
public String getDepartment() {
return this.department;
}

@Override
public String toString() {
return "HRs{" +
"name='" + name + '\'' +
", id=" + id +
", department='" + department + '\'' +
'}';
}
}
public class Engineer implements Employee {

private String name;
private int id;
private String department;

public Engineer(String name, int id, String department) {
this.name = name;
this.id = id;
this.department = department;
}

@Override
public String getName() {
return this.name;
}

@Override
public int getId() {
return this.id;
}

@Override
public String getDepartment() {
return this.department;
}

@Override
public String toString() {
return "Engineer{" +
"name='" + name + '\'' +
", id=" + id +
", department='" + department + '\'' +
'}';
}

}
public class SalesMan implements Employee {

private String name;
private int id;
private String department;

public SalesMan(String name, int id, String department) {
this.name = name;
this.id = id;
this.department = department;
}

@Override
public String getName() {
return this.name;
}

@Override
public int getId() {
return this.id;
}

@Override
public String getDepartment() {
return this.department;
}

@Override
public String toString() {
return "SalesMan{" +
"name='" + name + '\'' +
", id=" + id +
", department='" + department + '\'' +
'}';
}
}
public class Company {

public static void main(String[] args) {
List<Employee> employees = new ArrayList();
Employee eng = new Engineer("Aalishan", 1, "Tech");
Employee sales = new SalesMan("Santosh", 2, "Sale");
Employee hr = new HRs("Abc", 3, "Hr");
employees.add(eng);
employees.add(sales);
employees.add(hr);
for (Employee e : employees
) {
System.out.println(e.toString());
}
}

}

Behavioral Pattern

  1. Observer pattern:
public interface Subject {
void register(Observer observer);
void unRegister(Observer observer);
void notifyMessage(Message message);
}
public interface Observer {
void updateMessage(Message message);
}
public class Message {

private final String message;

Message(String msg) {
message = msg;
}

public String getMessage() {
return message;
}
}
public class MessagePublisher implements Subject {

// Collection of observers
private Set<Observer> observers = new HashSet<>();

@Override
public void register(Observer observer) {
observers.add(observer);
}

@Override
public void unRegister(Observer observer) {
observers.remove(observer);
}

@Override
public void notifyMessage(Message message) {
for (Observer one : observers
) {
one.updateMessage(message);
}
}

}
public class FirstSubscriber implements Observer {

@Override
public void updateMessage(Message message) {
System.out.println(message.getMessage());
}

}
public class SecondSubscriber implements Observer {

@Override
public void updateMessage(Message message) {
System.out.println(message.getMessage());
}

}
public class ObserverTest {

public static void main(String[] args) {
FirstSubscriber firstMessageSubscriber = new FirstSubscriber();
SecondSubscriber secondMessageSubscriber = new SecondSubscriber();
ThirdSubscriber thirdMessageSubscriber = new ThirdSubscriber();
//Creating Message Publisher
MessagePublisher messagePublisher = new MessagePublisher();
//Register two Subscribers to get notifications on any update
messagePublisher.register(firstMessageSubscriber);
messagePublisher.register(secondMessageSubscriber);
messagePublisher.register(thirdMessageSubscriber);
//firstMessageSubscriber and secondMessageSubscriber will receive the update
messagePublisher.notifyMessage(new Message("This is First Message"));
System.out.println("---------------------------------------------------------------");
}

}

--

--

--

Senior Android App Developer | Startup | Product base | Java | Kotlin | MVVM | Architecture components | Android Blogger

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

It’s all about the workflow: Mode Analytics

I Want to Learn Programming but I Don’t Know Where to Start

Ditch SSH for good, with AWS SSM Session Manager

ARKit in Swift

SICP: Applying Huffman Codes to Smashmouth

Using virtual hosts in XAMPP

Adding dimensions to numpy.arrays: newaxis v.s. reshape v.s. expand_dims

5 tips for QAs to add more value to their teams

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aalishan Ansari

Aalishan Ansari

Senior Android App Developer | Startup | Product base | Java | Kotlin | MVVM | Architecture components | Android Blogger

More from Medium

Design Patterns in Kotlin: Visitor

Design Patterns in Java/Android — Builder

Brief information about exceptions in Java/Android

Why Android developer ❤ to use Kotlin as a main language besides Java?