Design Patterns.
1. Creational
2. Structural
3. Behavourial
In Behvorial
1. Strategy pattern
Example :
Step 1
Create an interface.
Strategy.java
public interface Strategy { public int doOperation(int num1, int num2); }
Step 2
Create concrete classes implementing the same interface.
OperationAdd.java
public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; } }
OperationSubstract.java
public class OperationSubstract implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 - num2; } }
OperationMultiply.java
public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 * num2; } }
Step 3
Create Context Class.
Context.java
public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); } }
Step 4
Use the Context to see change in behaviour when it changes its Strategy.
StrategyPatternDemo.java
public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }
Step 5
Verify the output.
10 + 5 = 15 10 - 5 = 5 10 * 5 = 50
2. Null Object PatternIn Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available.
In Null Object pattern, we create an abstract class specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implemention of this class and will be used seemlessly where we need to check null value.
Implementation
We are going to create a AbstractCustomer abstract class defining opearations. Here the name of the customer and concrete classes extending the AbstractCustomer class. A factory class CustomerFactory is created to return either RealCustomer or NullCustomer objects based on the name of customer passed to it.
NullPatternDemo, our demo class, will use CustomerFactory to demonstrate the use of Null Object pattern
ExampleStep 1
Create an abstract class.
AbstractCustomer.java
public abstract class AbstractCustomer { protected String name; public abstract boolean isNil(); public abstract String getName(); }Step 2
Create concrete classes extending the above class.
RealCustomer.java
public class RealCustomer extends AbstractCustomer { public RealCustomer(String name) { this.name = name; } @Override public String getName() { return name; } @Override public boolean isNil() { return false; } }NullCustomer.java
public class NullCustomer extends AbstractCustomer { @Override public String getName() { return "Not Available in Customer Database"; } @Override public boolean isNil() { return true; } }Step 3
Create CustomerFactory Class.
CustomerFactory.java
public class CustomerFactory { public static final String[] names = {"Rob", "Joe", "Julie"}; public static AbstractCustomer getCustomer(String name){ for (int i = 0; i < names.length; i++) { if (names[i].equalsIgnoreCase(name)){ return new RealCustomer(name); } } return new NullCustomer(); } }Step 4
Use the CustomerFactory to get either RealCustomer or NullCustomer objects based on the name of customer passed to it.
NullPatternDemo.java
public class NullPatternDemo { public static void main(String[] args) { AbstractCustomer customer1 = CustomerFactory.getCustomer("Rob"); AbstractCustomer customer2 = CustomerFactory.getCustomer("Bob"); AbstractCustomer customer3 = CustomerFactory.getCustomer("Julie"); AbstractCustomer customer4 = CustomerFactory.getCustomer("Laura"); System.out.println("Customers"); System.out.println(customer1.getName()); System.out.println(customer2.getName()); System.out.println(customer3.getName()); System.out.println(customer4.getName()); } }Step 5
Verify the output.
Customers Rob Not Available in Customer Database Julie Not Available in Customer Database3. State PatternAnother Example
public class ReceiptStateActivity implements Processor {event = ReceiptRulesState.start(receipt);}public class ReceiptRulesState
extends AbstractRulesState<Receipt, Order, ReceiptStateResponseEvent, ReceiptStateResponseEvent> {public static ReceiptStateResponseEvent start(Receipt ReceiptRequestPayload) throws Exception {
ReceiptRulesState receiptRulesState = new ReceiptRulesState();
return receiptRulesState.execute(ReceiptRequestPayload);
}}public abstract class AbstractRulesState <T, C, R, K> extends AbstractRulesFilterState<T, C> implements IRulesEngine<T> {public R execute(T target) throws Exception{
this.run();
return this.getResponse();
}}public class ReturnRulesState
extends
AbstractRulesState <Order, OrderLine, Order, OrderQuantity> {@Override
public void run() {
runStateExecutorCompletionService(executorService);
}}4. Observer patternObserver pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.
Implementation
Observer pattern uses three actor classes. Subject, Observer and Client. Subject is an object having methods to attach and detach observers to a client object. We have created an abstract class Observer and a concrete class Subject that is extending class Observer.
ObserverPatternDemo, our demo class, will use Subject and concrete class object to show observer pattern in action.
Step 1
Create Subject class.
Subject.java
import java.util.ArrayList; import java.util.List; public class Subject { private List<Observer> observers = new ArrayList<Observer>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObservers(); } public void attach(Observer observer){ observers.add(observer); } public void notifyAllObservers(){ for (Observer observer : observers) { observer.update(); } } }Step 2
Create Observer class.
Observer.java
public abstract class Observer { protected Subject subject; public abstract void update(); }Step 3
Create concrete observer classes
BinaryObserver.java
public class BinaryObserver extends Observer{ public BinaryObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Binary String: " + Integer.toBinaryString( subject.getState() ) ); } }OctalObserver.java
public class OctalObserver extends Observer{ public OctalObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Octal String: " + Integer.toOctalString( subject.getState() ) ); } }HexaObserver.java
public class HexaObserver extends Observer{ public HexaObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "Hex String: " + Integer.toHexString( subject.getState() ).toUpperCase() ); } }Step 4
Use Subject and concrete observer objects.
ObserverPatternDemo.java
public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject(); new HexaObserver(subject); new OctalObserver(subject); new BinaryObserver(subject); System.out.println("First state change: 15"); subject.setState(15); System.out.println("Second state change: 10"); subject.setState(10); } }Step 5
Verify the output.
First state change: 15 Hex String: F Octal String: 17 Binary String: 1111 Second state change: 10 Hex String: A Octal String: 12 Binary String: 1010
Comments
Post a Comment