The strategy pattern is also a pattern we often use. Its definition is as follows: the variable part is abstracted from the program to become the algorithm interface, and a series of algorithm implementations are encapsulated under this part and can be replaced with each other.
For example, we now have three payment methods: Alipay payment, WeChat payment, and bank App payment. Suppose we want to make a software, and each software has its own corresponding payment method. In this case, we can separate the payment method as a strategy, and it is very convenient to use the one we want to use when writing software classes. strategic approach.
The strategy is made into an interface, and then the software is made into an abstract class, so that each specific software class and specific strategy class can be easily written through inheritance. The implementation code is as follows:
PayStrategy.java // Payment strategy interface public interface PayStrategy { void pay(); } WeiXin.java public class WeiXin implements PayStrategy { // WeChat payment class @Override public void pay() { // TODO Auto-generated method stub System.out.println("---Please use WeChat Pay---" ); } } Zhifubao.java public class Zhifubao implements PayStrategy { // Alipay payment class @Override public void pay() { // TODO Auto-generated method stub System.out.println("---Please use Alipay to pay---" ); } }
BanApp.java public class BankApp implements PayStrategy { // Bank App payment class @Override public void pay() { // TODO Auto-generated method stub System.out.println("---Please use the bank app to pay---" ); } }
Then use a software abstract class, and the required concrete software class.
PaySoftware.java // Software abstract class public abstract class Paysoftware { // Use combination to implement strategy mode private PayStrategy strategy; public void setStrategy(PayStrategy strategy) { this.strategy = strategy; } public void payInterface() { strategy.pay(); } // There is no method using the strategy pattern public abstract void sofwareStatement(); } SoftwareA.java public class SoftwareA extends Paysoftware { public SoftwareA() { // TODO Auto-generated constructor stub super(); super.setStrategy(new Zhifubao()); } public void sofwareStatement () { System.out.println( "I am software A" ); } } SoftwareB.java public class SoftWareB extends Paysoftware { public SoftWareB() { // TODO Auto-generated constructor stub super(); super.setStrategy(new BankApp()); } public void sofwareStatement () { System.out.println( "I am software B" ); } }
define another test class
TestDrive.java public class TestDrive { public static void main(String[] args) { // TODO Auto-generated method stub Paysoftware softwarea=new SoftwareA(); software.sofwareStatement (); software.payInterface (); } }
The result is as follows:
I am software A
---Please use Alipay to pay---
This way we implement the strategy pattern.