当前位置:网站首页>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
边栏推荐
- 获取前一天的js(时间戳转换)
- go 文件路径操作
- Redis唯一ID生成器的实现
- 台风来袭!建筑工地该如何防范台风!
- Monorepo管理方法论和依赖安全
- ts 之 类的简介、构造函数和它的this、继承、抽象类、接口
- The Chinese Academy of Management Sciences gathered industry experts, and Fu Qiang won the title of "top ten youth" of think tank experts
- PHP反序列化+MD5碰撞
- Duchefa丨低熔点琼脂糖 PPC中英文说明书
- 14、Transformer--VIT TNT BETR
猜你喜欢

Wanglaoji pharmaceutical's public welfare activity of "caring for the most lovely people under the scorching sun" was launched in Nanjing

当Steam教育进入个性化信息技术课程

学习机器人无从下手?带你体会当下机器人热门研究方向有哪些

Typhoon is coming! How to prevent typhoons on construction sites!

基于AVFoundation实现视频录制的两种方式

XML建模

Duchefa丨低熔点琼脂糖 PPC中英文说明书

解读协作型机器人的日常应用功能

When steam education enters personalized information technology courses

Which is the best online collaboration product? Microsoft loop, notion, flowus
随机推荐
Redis唯一ID生成器的实现
ts 之 类的简介、构造函数和它的this、继承、抽象类、接口
Duchefa细胞分裂素丨二氢玉米素 (DHZ)说明书
Selenium element information
Make Jar, Not War
Abnova maxpab mouse derived polyclonal antibody solution
Material design component - use bottomsheet to show extended content (II)
清除app data以及获取图标
Kubernetes resource object introduction and common commands (V) - (configmap & Secret)
如何让化工企业的ERP库存账目更准确
Abbkine trakine F-actin Staining Kit (green fluorescence) scheme
go 文件路径操作
MYSQL IFNULL使用功能
当用户登录,经常会有实时的下拉框,例如,输入邮箱,将会@qq.com,@163.com,@sohu.com
Applet global configuration
[quick start of Digital IC Verification] 2. Through an example of SOC project, understand the architecture of SOC and explore the design process of digital system
国外LEAD美国简称对照表
从架构上详解技术(SLB,Redis,Mysql,Kafka,Clickhouse)的各类热点问题
线程池的使用
[record of question brushing] 1 Sum of two numbers