The-openclosed-principle:
Open to Extension:
Collections. Sort(<>, comparator)
- It is just the comparator implementation,
going to be changed.
Closed for
Modification
- If behavior changes,
we should not be changing the entities
-
implementation closed to modification
-Sort
method is not going to change
One of the strategy
‘Program by Interface, not by Implementation’ helps to achieve this
Backed by strategy
pattern (behavior)
Strategy
Pattern:
Encapsulate the
strategies and decide what to use depending on some specific conditions.
StrategyClassà implements Strategy interface
Context Class <uses> strategy classes
Sample
//Define Strategy
public class ServiceInvoker
{
public void invokeSomething();
}
//Strategy1
NasdaqApiInvoker implements
ServiceInvoker {
public void invokeSomething(){
}
}
//Strategy2
NikkeiApiInvoker implements
ServiceInvoker {
public void invokeSomething(){
}
}
//Context class to
inject strategy
SockPriceFetcher
ServiceInvoker serviceInvoker;
StockPriceFetcher
(ServiceInvoker serviceInvoker ){
this.serviceInvoker=
serviceInvoker;
}
fetchStockValue(){
serviceInvoker. invokeSomething()
}
}
//Client
Class GetStockData{
StockPriceFetcher stockPriceFetcher = new StockPriceFetcher (new NasdaqApiInvoker()) // StockPriceFetcher is decoupled with specific strategy
sockPriceFetcher. fetchStockValue
()
StockPriceFetcher stockPriceFetcher2= new StockPriceFetcher (new NikkeiApiInvoker ()};
stockPriceFetcher2..
fetchStockValue ()
}