当前位置:网站首页>Mode - "Richter replacement principle"
Mode - "Richter replacement principle"
2022-07-05 20:51:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack
The Richter substitution principle is , There are two subclasses of a class in the same group , Using subclasses A This place ( Method / attribute ) You can use subclasses B Instead of . For interface oriented programming , I just need to make sure the same behavior code ; All subclasses of the base class must be all Realization , Change over , The method base classes of subclasses do not necessarily have ; If : There is a base class Base; Its subclass is Concrete; that method(Base b) The call of can be converted into method(Concrete c); The strategy pattern : commonly , We call the method of solving a problem a ” Algorithm ”, And encapsulate the algorithm for solving a class of problems Become an interface , Then there are many ways to implement the algorithm as subclasses ; At some point , In the call, we use the algorithm A Replace Algorithm B, This is the application of the strategic model in the principle of Richter's substitution ; *************** The strategy pattern ************************************ > Prepare a set of algorithms , And encapsulate each so that they can be interchanged .
Context
/**
* @author Lean @date:2014-10-17
*/
public class Context {
public static Strategy strategy;
public static void main(String[] args) {
strategy=new ConcreteStrategyA();
strategy.calculate();
}
}
abstract class Strategy{
public abstract void calculate();
}
class ConcreteStrategyA extends Strategy{
@Override
public void calculate() {
System.out.println("ConcreteStrategyA is called !");
}
}
class ConcreteStrategyB extends Strategy{
@Override
public void calculate() {
System.out.println("ConcreteStrategyB is called !");
}
IChoiceStrategy
/**
* selection strategy
*
* @author Lean @date:2014-10-17
*/
public abstract class IChoiceStrategy {
/**
* @return Return the list name
*/
public abstract String[] getNames();
/**
* @return Return the corresponding code
*/
public abstract int getCode(String name);
}
/**
* @author Lean @date:2014-10-17
*/
public class SortChoiceStrategy extends IChoiceStrategy {
private HashMap<String, Integer> mSortMap;
public String name;
public SortChoiceStrategy() {
initSortMap();
}
private void initSortMap() {
mSortMap=new HashMap<String, Integer>();
mSortMap.put(" New releases ", 0);
mSortMap.put(" Highest sales ", 1);
mSortMap.put(" Highest price ", 2);
mSortMap.put(" Lowest price ", 3);
name=" New releases ";
}
@Override
public String[] getNames() {
Set<String> set=mSortMap.keySet();
Object[] tempObj=set.toArray();
String[] result=new String[tempObj.length];
for (int i = 0; i < tempObj.length; i++) {
result[i]=(String) tempObj[i];
}
return result;
}
@Override
public int getCode(String name) {
return mSortMap.get(name);
}
}
/**
* @author Lean @date:2014-10-17
*/
public class StatusChoiceStrategy extends IChoiceStrategy {
private HashMap<String, Integer> mStatusMap;
public String name;
public StatusChoiceStrategy() {
initStatusMap();
}
private void initStatusMap() {
mStatusMap=new HashMap<String, Integer>();
mStatusMap.put(" Customization in progress ", 1);
mStatusMap.put(" It's over ", 2);
name=" Customization in progress ";
}
@Override
public String[] getNames() {
Set<String> set=mStatusMap.keySet();
Object[] tempObj=set.toArray();
String[] result=new String[tempObj.length];
for (int i = 0; i < tempObj.length; i++) {
result[i]=(String) tempObj[i];
}
return result;
}
@Override
public int getCode(String name) {
return mStatusMap.get(name);
}
}
***********************************************************
The proxy pattern : The delegate and the delegate have the same behavior , We encapsulate it as an interface , that , In being Proxy object replacement can be used wherever proxy object is called to hide implementation details ; *************** The proxy pattern ************************************ If a scene ,A Want to buy tickets , but A Don't have the time , therefore A Support B Go to the cinema and help him buy tickets ; Change to object-oriented thinking : If there is an object A, And a new object C, Now C Want to use objects A, and A Temporarily return Do not conform to the C The requirements of , At this time, it can be used indirectly B To use A Purpose , At the same time ,B It can also control the use process
Intercept , Such as printing logs ;( There are also adapter patterns that use the middle tier to achieve their goals )
/**
* @author Lean @date:2014-10-17
*/
public abstract class IPerson {
public abstract void buyTicket();
}
/**
* @author Lean @date:2014-10-17
*/
public class RealSeePerson extends IPerson {
@Override
public void buyTicket() {
System.out.println("RealSeePerson get the ticket !");
}
}
/**
* @author Lean @date:2014-10-17
*/
public class BuyTicketPerson extends IPerson{
public RealSeePerson target;
private void preBuyTicket(){
//TODO do th. before buy ticket
target=new RealSeePerson();
}
@Override
public void buyTicket() {
preBuyTicket();
if (target!=null) {
target.buyTicket();
}
postBuyTicket();
}
public void postBuyTicket(){
//TODO do th. after buy thicket
}
}
> The proxy and the proxied object implement a common interface , When the proxy object is called, the delegation of the proxy object is called ;
Dynamic agent realizes listening :
/**
* @author Lean @date:2014-10-17
*/
public class VectorProxy implements InvocationHandler {
private Object proxyobj;
public VectorProxy(Object obj) {
proxyobj=obj;
}
public static Object factor(Object obj){
Class cls=obj.getClass();
return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new VectorProxy(obj));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("method:"+method.getName());
if (args!=null) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]+"");
}
}
// Reflection call
Object obj=method.invoke(proxyobj, args);
System.out.println("*********");
return obj;
}
public static void main(String[] args) {
List v=null;
// Return proxy object , And call the add Method
v=(List) factor(new Vector(10));
v.add("New");
}
}
***********************************************************
Synthesis mode : The above two models are the application of Richter's substitution principle in methods . Synthetic patterns use tree results to describe narratives The relationship between the whole and the part , Because simple elements and composite elements implement abstraction in the same way , So where abstraction is used , Can this 2 Element substitution ; *************** Synthesis mode ************************************
The synthesis mode is divided into transparent and safe
transparent : An abstract interface declares all interface methods of all branches , In leaves . Empty the method ;
/**
* @author Lean @date:2014-10-20
*/
public interface Component {
void sampleOperation();
Composite getComposite();
void add(Component component);
void remove(Component component);
Enumeration<Component> components();
}
/**
* @author Lean @date:2014-10-20
*/
public class Composite implements Component {
private Vector<Component> componentVector=new Vector<Component>();
@Override
public Composite getComposite() {
return this;
}
@Override
public void sampleOperation() {
Enumeration<Component> enumeration=components();
while (enumeration.hasMoreElements()) {
Component component = (Component) enumeration.nextElement();
component.sampleOperation();
}
}
@Override
public void add(Component component) {
componentVector.addElement(component);
}
@Override
public void remove(Component component) {
componentVector.removeElement(component);
}
@Override
public Enumeration<Component> components() {
return componentVector.elements();
}
}
/**
* @author Lean @date:2014-10-20
*/
public class Leaf implements Component {
@Override
public Composite getComposite() {
return null;
}
@Override
public void sampleOperation() {
System.out.println(" call leaf here !");
}
@Override
public void add(Component component) {
}
@Override
public void remove(Component component) {
}
@Override
public Enumeration<Component> components() {
return null;
}
}
Security : It means that the abstract interface only declares all the methods of the leaf , In addition to inheritance, the branch class also includes its own methods for managing leaf classes ; Typical applications :Android Of View,ViewGroup
/**
* @author Lean @date:2014-10-20
*/
public interface Component {
Composite getComposite();
void sampleOperation();
}
/**
* @author Lean @date:2014-10-20
*/
public class Composite implements Component {
private Vector componentVector=new Vector();
@Override
public void sampleOperation() {
Enumeration enumeration=components();
while (enumeration.hasMoreElements()) {
((Component) enumeration.nextElement()).sampleOperation();
}
}
@Override
public Composite getComposite() {
return this;
}
public Enumeration components(){
return componentVector.elements();
}
public void add(Component component){
componentVector.addElement(component);
}
public void remove(Component component){
componentVector.removeElement(component);
}
}
/**
* @author Lean @date:2014-10-20
*/
public class Leaf implements Component {
@Override
public Composite getComposite() {
return null;
}
@Override
public void sampleOperation() {
System.out.println("leaf is called !");
}
}
Because branches basically inherit abstract classes , Only classes are supported in abstract methods , There can be replaced with a leaf . for example , In safe mode . Leaves can be replaced with rods / Leafy ; Interchangeable in transparent mode . This is the principle of substitution with Richter ;
***********************************************************
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/117666.html Link to the original text :https://javaforall.cn
边栏推荐
猜你喜欢
Wanglaoji pharmaceutical's public welfare activity of "caring for the most lovely people under the scorching sun" was launched in Nanjing
Duchefa丨MS培养基含维生素说明书
Phpstudy Xiaopi's MySQL Click to start and quickly flash back. It has been solved
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
PHP deserialization +md5 collision
Specification of protein quantitative kit for abbkine BCA method
haas506 2.0开发教程 - 阿里云ota - pac 固件升级(仅支持2.2以上版本)
CADD course learning (7) -- Simulation of target and small molecule interaction (semi flexible docking autodock)
Use of thread pool
表单文本框的使用(二) 输入过滤(合成事件)
随机推荐
mysql全面解析json/数组
Popular science | does poor English affect the NPDP exam?
CCPC 2021 Weihai - G. shinyruo and KFC (combination number, tips)
Abnova total RNA Purification Kit for cultured cells Chinese and English instructions
Abnova DNA marker high quality control test program
渗透创客精神文化转化的创客教育
产品好不好,谁说了算?Sonar提出分析的性能指标,帮助您轻松判断产品性能及表现
CareerCup它1.8 串移包括问题
Write an interface based on flask
Use of thread pool
Abnova丨培养细胞总 RNA 纯化试剂盒中英文说明书
Usaco3.4 "broken Gong rock" band raucous rockers - DP
Applet event binding
研學旅遊實踐教育的開展助力文旅產業發展
Abnova CRISPR spcas9 polyclonal antibody protocol
Norgen AAV提取剂盒说明书(含特色)
bazel是否有学习的必要
PHP反序列化+MD5碰撞
当用户登录,经常会有实时的下拉框,例如,输入邮箱,将会@qq.com,@163.com,@sohu.com
Abnova e (diii) (WNV) recombinant protein Chinese and English instructions