<>1) Shopping mall cashier system
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import
javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.
JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.
JPanel; import javax.swing.JTextField; /** * Shopping mall cashier system */ @SuppressWarnings(
"serial") public class Mall implements ActionListener { private static JLabel
unitPriceLabel; private static JTextField unitPriceValue; private static JLabel
numLabel; private static JTextField numValue; private double totalPrice = 0;
private static JList<String> jList; private static DefaultListModel<String>
listModel; private static JLabel totalNum; public static void main(String[] args
) { JFrame frame = new JFrame(" Mall cashier system "); frame.setSize(450, 400); frame.
setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
); JPanel panel = new JPanel(); frame.add(panel); placeComponents(panel); frame.
setVisible(true); } private static void placeComponents(JPanel panel) { panel.
setLayout(null); Mall mainFrame = new Mall(); // first line unitPriceLabel = new JLabel
(" Unit Price :"); unitPriceLabel.setBounds(10, 20, 80, 25); panel.add(unitPriceLabel);
unitPriceValue= new JTextField(20); unitPriceValue.setBounds(100, 20, 165, 25);
panel.add(unitPriceValue); JButton confirmButton = new JButton(" determine ");
confirmButton.setBounds(280, 20, 80, 25); confirmButton.addActionListener(
mainFrame); confirmButton.setActionCommand("confirm"); panel.add(confirmButton);
// Second line numLabel = new JLabel(" quantity :"); numLabel.setBounds(10, 50, 80, 25); panel.
add(numLabel); numValue = new JTextField(20); numValue.setBounds(100, 50, 165,
25); panel.add(numValue); JButton resetButton = new JButton(" Reset "); resetButton.
setBounds(280, 50, 80, 25); resetButton.addActionListener(mainFrame);
resetButton.setActionCommand("reset"); panel.add(resetButton); // Third line listModel
= new DefaultListModel<String>(); jList = new JList<String>(listModel); jList.
setBounds(10, 90, 400, 180); panel.add(jList); // Fourth line JLabel totalLabel = new
JLabel(" total :"); totalLabel.setBounds(10, 300, 80, 25); panel.add(totalLabel);
totalNum= new JLabel("0.00"); totalNum.setBounds(100, 300, 80, 25); panel.add(
totalNum); } @Override public void actionPerformed(ActionEvent event) { if (
event.getActionCommand().equals("confirm")) { double unitPrice = Double.
parseDouble(unitPriceValue.getText()); double num = Double.parseDouble(numValue.
getText()); double total = unitPrice * num; listModel.addElement(" Unit Price :"+
unitPriceValue.getText()+" quantity :"+numValue.getText() +" total :"+total); totalPrice +=
total; totalNum.setText(totalPrice+""); } else if(event.getActionCommand().
equals("reset")) { unitPriceValue.setText(""); numValue.setText(""); listModel.
clear(); totalPrice=0; totalNum.setText(totalPrice+""); } } }
<> Execution effect

<>2) Add discount function
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import
javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.
JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.
swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; /** *
demand : Add discount function */ @SuppressWarnings("serial") public class Mall implements
ActionListener { private static JLabel unitPriceLabel; private static JTextField
unitPriceValue; private static JLabel numLabel; private static JTextField
numValue; private double totalPrice = 0; private static JList<String> jList;
private static DefaultListModel<String> listModel; private static JLabel
totalNum; private static JLabel calcType; private static JComboBox<String>
jComboBox; public static void main(String[] args) { JFrame frame = new JFrame(
" Mall cashier system "); frame.setSize(450, 400); frame.setLocationRelativeTo(null); frame.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel();
frame.add(panel); placeComponents(panel); frame.setVisible(true); } private
static void placeComponents(JPanel panel) { panel.setLayout(null); Mall
mainFrame= new Mall(); // first line unitPriceLabel = new JLabel(" Unit Price :"); unitPriceLabel
.setBounds(10, 20, 80, 25); panel.add(unitPriceLabel); unitPriceValue = new
JTextField(20); unitPriceValue.setBounds(100, 20, 165, 25); panel.add(
unitPriceValue); JButton confirmButton = new JButton(" determine "); confirmButton.
setBounds(280, 20, 80, 25); confirmButton.addActionListener(mainFrame);
confirmButton.setActionCommand("confirm"); panel.add(confirmButton); // Second line
numLabel= new JLabel(" quantity :"); numLabel.setBounds(10, 50, 80, 25); panel.add(
numLabel); numValue = new JTextField(20); numValue.setBounds(100, 50, 165, 25);
panel.add(numValue); JButton resetButton = new JButton(" Reset "); resetButton.
setBounds(280, 50, 80, 25); resetButton.addActionListener(mainFrame);
resetButton.setActionCommand("reset"); panel.add(resetButton); // Third line calcType =
new JLabel(" Calculation method :"); calcType.setBounds(10, 90, 80, 25); panel.add(calcType);
jComboBox= new JComboBox<String>(); jComboBox.insertItemAt(" Normal charge ", 0); jComboBox
.insertItemAt(" 20% off ", 1); jComboBox.insertItemAt(" 30% off ", 2); jComboBox.
insertItemAt(" 50% off ", 3); jComboBox.setSelectedIndex(0); jComboBox.setBounds(100,
90, 80, 25); panel.add(jComboBox); // Fourth line listModel = new DefaultListModel<
String>(); jList = new JList<String>(listModel); jList.setBounds(10, 120, 400,
180); panel.add(jList); // The fifth line JLabel totalLabel = new JLabel(" total :"); totalLabel
.setBounds(10, 300, 80, 25); panel.add(totalLabel); totalNum = new JLabel("0.00"
); totalNum.setBounds(100, 300, 80, 25); panel.add(totalNum); } @Override public
void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals(
"confirm")) { double unitPrice = Double.parseDouble(unitPriceValue.getText());
double num = Double.parseDouble(numValue.getText()); int selectedIndex =
jComboBox.getSelectedIndex(); double total = 0; switch (selectedIndex) { case 0:
total= unitPrice * num; break; case 1: total = unitPrice * num * 0.8; break;
case 2: total = unitPrice * num * 0.7; break; case 3: total = unitPrice * num *
0.5; break; } totalPrice += total; listModel.addElement(" Unit Price :" + unitPriceValue.
getText() + " quantity :" + numValue.getText() + " " + jComboBox.getSelectedItem() + "
total :" + total); totalNum.setText(totalPrice + ""); } else if (event.
getActionCommand().equals("reset")) { unitPriceValue.setText(""); numValue.
setText(""); listModel.clear(); totalPrice = 0; totalNum.setText(totalPrice + ""
); } } }
<> Execution effect

<>3) Simple factory implementation

problem : If the increase is full 300 return 100 Sales promotion algorithm , How to deal with it ?
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import
javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.
JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.
swing.JList; import javax.swing.JPanel; import javax.swing.JTextField;
@SuppressWarnings("serial") public class Mall implements ActionListener {
private static JLabel unitPriceLabel; private static JTextField unitPriceValue;
private static JLabel numLabel; private static JTextField numValue; private
double totalPrice = 0; private static JList<String> jList; private static
DefaultListModel<String> listModel; private static JLabel totalNum; private
static JLabel calcType; private static JComboBox<String> jComboBox; public
static void main(String[] args) { JFrame frame = new JFrame(" Mall cashier system "); frame.
setSize(450, 400); frame.setLocationRelativeTo(null); frame.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel();
frame.add(panel); placeComponents(panel); frame.setVisible(true); } private
static void placeComponents(JPanel panel) { panel.setLayout(null); Mall
mainFrame= new Mall(); // first line unitPriceLabel = new JLabel(" Unit Price :"); unitPriceLabel
.setBounds(10, 20, 80, 25); panel.add(unitPriceLabel); unitPriceValue = new
JTextField(20); unitPriceValue.setBounds(100, 20, 165, 25); panel.add(
unitPriceValue); JButton confirmButton = new JButton(" determine "); confirmButton.
setBounds(280, 20, 80, 25); confirmButton.addActionListener(mainFrame);
confirmButton.setActionCommand("confirm"); panel.add(confirmButton); // Second line
numLabel= new JLabel(" quantity :"); numLabel.setBounds(10, 50, 80, 25); panel.add(
numLabel); numValue = new JTextField(20); numValue.setBounds(100, 50, 165, 25);
panel.add(numValue); JButton resetButton = new JButton(" Reset "); resetButton.
setBounds(280, 50, 80, 25); resetButton.addActionListener(mainFrame);
resetButton.setActionCommand("reset"); panel.add(resetButton); // Third line calcType =
new JLabel(" Calculation method :"); calcType.setBounds(10, 90, 80, 25); panel.add(calcType);
jComboBox= new JComboBox<String>(); jComboBox.insertItemAt(" Normal charge ", 0); jComboBox
.insertItemAt(" hit 8 fracture ", 1); jComboBox.insertItemAt(" full 300 return 100", 2); jComboBox.
setSelectedIndex(0); jComboBox.setBounds(100, 90, 80, 25); panel.add(jComboBox);
// Fourth line listModel = new DefaultListModel<String>(); jList = new JList<String>(
listModel); jList.setBounds(10, 120, 400, 180); panel.add(jList); // The fifth line JLabel
totalLabel= new JLabel(" total :"); totalLabel.setBounds(10, 300, 80, 25); panel.add(
totalLabel); totalNum = new JLabel("0.00"); totalNum.setBounds(100, 300, 80, 25)
; panel.add(totalNum); } @Override public void actionPerformed(ActionEvent event
) { if (event.getActionCommand().equals("confirm")) { double unitPrice = Double.
parseDouble(unitPriceValue.getText()); double num = Double.parseDouble(numValue.
getText()); CashSuper cashSuper = CashFactory.createashAccept(jComboBox.
getSelectedItem().toString()); double total = cashSuper.acceptCash(unitPrice *
num); totalPrice += total; listModel.addElement(" Unit Price :" + unitPriceValue.getText()
+ " quantity :" + numValue.getText() + " " + jComboBox.getSelectedItem() + " total :" +
total); totalNum.setText(totalPrice + ""); } else if (event.getActionCommand().
equals("reset")) { unitPriceValue.setText(""); numValue.setText(""); listModel.
clear(); totalPrice = 0; totalNum.setText(totalPrice + ""); } } } /** * Cash charge abstract class
*/ public abstract class CashSuper { /** * Abstract method of cash collection superclass , Cash collection , Parameter is original price , Return to current price */
public abstract double acceptCash(double money); } /** * Normal charge subclass */ public class
CashNormal extends CashSuper{ /** * Normal charge , Return of original price */ public double acceptCash(double
money) { return money; } } /** * Discount charge subclass */ public class CashRebate extends
CashSuper { private double moneyRebate = 1d; public CashRebate(String
moneyRebate) { this.moneyRebate = Double.parseDouble(moneyRebate); } /** *
Discount charge , During initialization , Discount rate must be entered , Such as 20% discount , namely 0.8 */ public double acceptCash(double money) { return
money* moneyRebate; } } /** * Rebate charge subclass */ public class CashReturn extends
CashSuper { private double moneyCondition = 0.0d; private double moneyReturn =
0.0d; /** * Rebate conditions and return values must be entered during initialization , Like full 300 return 100 * * @param moneyCondition 300 * @param
moneyReturn 100 */ public CashReturn(String moneyCondition, String moneyReturn)
{ this.moneyCondition = Double.parseDouble(moneyCondition); this.moneyReturn =
Double.parseDouble(moneyReturn); } public double acceptCash(double money) {
double result = money; // If greater than rebate condition , You need to subtract the rebate value if (money >= moneyCondition) { result
= money - Math.floor(money / moneyCondition) * moneyReturn; // Round down } return
result; } } /** * Charging object generation factory */ public class CashFactory { public static CashSuper
createashAccept(String type) { CashSuper cs = null; switch (type) { case " Normal charge ":
cs= new CashNormal(); break; case " full 300 return 100": cs = new CashReturn("300", "100")
; break; case " hit 8 fracture ": cs = new CashRebate("0.8"); break; } return cs; } }
<> Execution effect

problem : If the increase is full 100 integral 10 spot , What should I do ?
1) Add an integral algorithm , The construction method has two parameters : Conditions and rebates
2) Add full in the charging object generation factory 100 integral 10 Branching condition of point , Then go to the interface and make some changes
*

Although the simple factory model can also solve this problem , But this pattern only solves the problem of object creation , And because the factory itself includes all charging modes , Shopping malls may often change the discount limit and rebate limit , Every time you maintain or expand the charging method, you have to change the factory , So that the code needs to be recompiled and deployed , So this is not the best way , In the face of frequent changes in algorithms , Policy mode should be used .
How to promote sales at checkout in shopping malls , Discount or rebate , In fact, they are all algorithms , Using factories to generate algorithms , There's nothing wrong with that , but
The algorithm itself is just a strategy , Most importantly, these algorithms may replace each other at any time , This is the point of change , Encapsulating change points is a very important way of thinking in object-oriented .

<>4) Strategy mode
/** * Abstract algorithm class */ public abstract class Strategy { // Algorithm method public abstract void
AlgorithmInterface(); } /** * Specific algorithm A */ public class ConcreteStrategyA extends
Strategy{ @Override public void AlgorithmInterface() { System.out.println(
" algorithm A realization "); } } /** * Specific algorithm B */ public class ConcreteStrategyB extends Strategy{
@Override public void AlgorithmInterface() { System.out.println(" algorithm B realization "); } }
/** * Specific algorithm C */ public class ConcreteStrategyC extends Strategy{ @Override public
void AlgorithmInterface() { System.out.println(" algorithm C realization "); } } /** * context */ public
class Context { Strategy strategy; // During initialization , Pass in a specific policy object public Context(Strategy
strategy) { this.strategy = strategy; } // Context interface public void ContextInterface()
{ // According to the specific policy object , Method to call its algorithm strategy.AlgorithmInterface(); } }
client
/** * Client object */ public class Client { public static void main(String[] args) {
// Due to instantiation of different policies , So it's finally called context.ContextInterface() Time , The results obtained are different Context context =
new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new
Context(new ConcreteStrategyB()); context.ContextInterface(); context = new
Context(new ConcreteStrategyC()); context.ContextInterface(); } }
<>5) Policy mode implementation

Just add one CashContext class , Just rewrite the interface again .
public class CashContext { private CashSuper cs; // By construction method , Pass in specific charging strategy public
CashContext(CashSuper csuper) { this.cs = csuper; } public double getResult(
double money) { // According to different charging strategies , Obtain calculation results return cs.acceptCash(money); } }
Interface logic modification
if (event.getActionCommand().equals("confirm")) { double unitPrice = Double.
parseDouble(unitPriceValue.getText()); double num = Double.parseDouble(numValue.
getText()); CashContext cashContext = null; //
According to the drop-down selection box , Pass in the corresponding policy object as a parameter CashContext Objects in switch (jComboBox.getSelectedItem().
toString()) { case " Normal charge ": cashContext = new CashContext(new CashNormal());
break; case " full 300 return 100": cashContext = new CashContext(new CashReturn("300",
"100")); break; case " hit 8 fracture ": cashContext = new CashContext(new CashRebate("0.8"))
; break; } // Pass on Context of getResult Method call , You can get the result of charging , The specific algorithm is isolated from the customer . double total
= cashContext.getResult(unitPrice*num); totalPrice += total; listModel.
addElement(" Unit Price :" + unitPriceValue.getText() + " quantity :" + numValue.getText() + " "
+ jComboBox.getSelectedItem() + " total :" + total); totalNum.setText(totalPrice +
""); }
<> Execution effect

<>6) Strategy mode + Simple factory

Escape the judgment process in the interface to CashContext in .
public class CashContext { private CashSuper cs; //
Note that the parameter is not a specific charging policy object , It's a string , Indicates the type of charge public CashContext(String type) { switch (type) {
case " Normal charge ": // Transfer the process of instantiating a specific policy from the client to the Context In class , Application of simple factory cs = new CashNormal(); break
; case " full 300 return 100": cs = new CashReturn("300", "100"); break; case " hit 8 fracture ": cs =
new CashRebate("0.8"); break; } } public double getResult(double money) { //
According to different charging strategies , Obtain calculation results return cs.acceptCash(money); } }
Interface code
if (event.getActionCommand().equals("confirm")) { double unitPrice = Double.
parseDouble(unitPriceValue.getText()); double num = Double.parseDouble(numValue.
getText()); CashContext cashContext = new CashContext(jComboBox.getSelectedItem(
).toString()); double total = cashContext.getResult(unitPrice*num); totalPrice
+= total; listModel.addElement(" Unit Price :" + unitPriceValue.getText() + " quantity :" +
numValue.getText() + " " + jComboBox.getSelectedItem() + " total :" + total);
totalNum.setText(totalPrice + ""); }
<> The difference between simple factory and strategic mode
// Simple factory mode CashSuper cashSuper = CashFactory.createashAccept(jComboBox.
getSelectedItem().toString()); double total = cashSuper.acceptCash(unitPrice*num
); // Usage of policy pattern combined with simple factory CashContext cashContext = new CashContext(jComboBox.
getSelectedItem().toString()); double total = cashContext.getResult(unitPrice*
num);
Simple factory mode , Clients need to know CashSuper and CashFactory Two classes .
The use of strategy mode combined with simple factory , The client only needs to know one class CashContext That's it . Lower coupling .

<> Policy mode analysis

A policy pattern is a way to define a series of algorithms , Conceptually , All these algorithms do the same work , It's just different , It can call all algorithms in the same way , It reduces the coupling between various algorithm classes and using algorithm classes .

Policy mode Strategy Class level is Context Defines a series of reusable algorithms or behaviors . Inheritance helps to analyze the common functions in these algorithms .

The advantage of the policy pattern is that it simplifies unit testing , Because each algorithm has its own class , It can be tested separately through its own interface .

When different behaviors are stacked in a class , It is difficult to avoid using conditional statements to choose the appropriate behavior . Encapsulate these behaviors in separate Strategy In class , Conditional statements can be eliminated in classes that use these behaviors . That is, the policy pattern encapsulates the change .

The policy pattern is used to encapsulate the algorithm , But in practice , We found that it can be used to encapsulate almost any type of rule ,
As long as you hear in the analysis process, you need to apply different business rules at different times , You can consider the possibility of using a policy pattern to deal with this change .

In the basic policy mode , The responsibility for selecting the specific implementation used is borne by the client object , Mode and transfer to Context object . This in itself does not relieve the pressure on the client to choose judgment , After the combination of strategy mode and simple factory mode , The specific responsibilities can also be selected by Context To bear , This minimizes client responsibilities .

Technology
©2019-2020 Toolsou All rights reserved,
【C++ Must see for entry 】C++ from 0 reach 1 Introductory programming axios Interceptor packaging and use Spring Boot Interview must ask : Automatic configuration principle VMware 16 install centos 7 Detailed tutorial C Language data structure - Sequence table delete duplicates V2.0.0 The 12th Blue Bridge Cup c++b Group personal problem solving On sending data from serial port single chip microcomputer to upper computer centos7 install RabbitMqjava Polymorphic array of opencv-python Fourier transform and inverse transform