当前位置:网站首页>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
边栏推荐
- Abnova blood total nucleic acid purification kit pre installed relevant instructions
- 如何让化工企业的ERP库存账目更准确
- shell编程100例
- 手机开户股票开户安全吗?我家比较偏远,有更好的开户途径么?
- 模式-“里氏替换原则”
- bazel是否有学习的必要
- Popular science | does poor English affect the NPDP exam?
- Monorepo管理方法论和依赖安全
- 教你自己训练的pytorch模型转caffe(二)
- Écrire une interface basée sur flask
猜你喜欢
Return to blowing marshland -- travel notes of zhailidong, founder of duanzhitang
当Steam教育进入个性化信息技术课程
Use of thread pool
Frequent MySQL operations cause table locking problems
2.<tag-哈希表, 字符串>补充: 剑指 Offer 50. 第一个只出现一次的字符 dbc
PHP反序列化+MD5碰撞
Make Jar, Not War
台风来袭!建筑工地该如何防范台风!
phpstudy小皮的mysql点击启动后迅速闪退,已解决
Abnova丨DNA 标记高质量控制测试方案
随机推荐
Duchefa丨MS培养基含维生素说明书
重上吹麻滩——段芝堂创始人翟立冬游记
手机开户股票开户安全吗?我家比较偏远,有更好的开户途径么?
渗透创客精神文化转化的创客教育
How to open an account online for futures? Is it safe?
Monorepo管理方法论和依赖安全
Monorepo management methodology and dependency security
Abnova CRISPR spcas9 polyclonal antibody protocol
解析五育融合之下的steam教育模式
Prosci LAG-3 recombinant protein specification
Duchefa p1001 plant agar Chinese and English instructions
教你自己训练的pytorch模型转caffe(一)
《SAS编程和数据挖掘商业案例》学习笔记# 19
王老吉药业“关爱烈日下最可爱的人”公益活动在南京启动
中国的软件公司为什么做不出产品?00后抛弃互联网;B站开源的高性能API网关组件|码农周刊VIP会员专属邮件周报 Vol.097
Is it safe to open an account online? Where can I get a low commission?
Abnova丨荧光染料 620-M 链霉亲和素方案
Which is the best online collaboration product? Microsoft loop, notion, flowus
证券开户选择哪个证券比较好?网上开户安全么?
模式-“里氏替换原则”