当前位置:网站首页>Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
2022-07-03 05:39:00 【Manon stayup】

GitHub The source code to share
WeChat search : Code the agriculture StayUp
Home address :https://gozhuyinglong.github.io
The source code to share :https://github.com/gozhuyinglong/blog-demos
1. A simple duck simulation game
Let's take a look at a duck simulation game first : All kinds of ducks will appear in the game , They are swimming in the water , Quack at the same time .
After some research :
The known duck species are : wild duck (Mallard Duck)、 red-head (Redhead Duck)、 Rubber duck (Rubber Duck).
The known behaviors of ducks are : swimming (Swim)、 Quack (Quack)、 Show me the look of a duck (Display).
Here's what these ducks look like :



Needs are clear , Open up !
1.1 It's time to show OO Technology ~
For reusability , Designed a duck superclass Duck, And let all kinds of ducks inherit this superclass :
- This superclass implements
swim()、quack()Method , Because each duck looks different , thereforedisplay()Specify as abstract method ( Of course, this class is also an abstract class ). - Each subclass implements
display()Method - Because rubber ducks don't “ Cackle ”, So rewrite
quack()Method is “ Squeak ”.
Here is UML Class diagram :
1.2 Change!!!
We know that an unchanging truth of software development is :“ change ”!
Now ask to add a duck behavior : flight (Fly), How do you do that ?
If you continue to use inheritance , Then a rubber duck can't fly , It still needs to be rewritten fly() Method . as follows :

If you add another duck : Decoy duck (Decoy Duck), This is a wooden duck , It doesn't call , I can't fly …
It seems that inheritance can't meet the demand !
1.3 How about using interfaces ?
take fly() Methods and quack() Pulled out , Make the interface , Let the duck with the behavior implement it . as follows :

It seems to solve the problem now !
But if you add more 100 A duck ? Not all ducks that can fly or bark , We have to do it all over again , The reusability of the code is not achieved . And once you want to modify a behavior, it will be a painful thing ( For example, all the “ Squeak ” Change to “ Simulation quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack quack ”)……
1.4 Packaging changes
There is a design principle , It's just right for the above simulation of duck game .
Find out what changes may be needed in the application , Separate them out , Don't mix with code that doesn't need to change .
let me put it another way , If every time there's a new demand , Will make a certain aspect of the code change , Then you can be sure , This part of the code needs to be pulled out , Different from other stable code .
This is the spirit of the strategic model , Let's take a look at the details of this model .
2. The strategy pattern
The strategy pattern (Strategy Pattern) It's a behavioral pattern . The pattern defines a series of algorithms , Encapsulate them one by one , And make them interchangeable . This pattern allows the algorithm to change independently of the customers who use it .
Define a family of algorithms, encapsulate each one, and make them interchangeable.
The design pattern embodies several design principles :
- Packaging changes
- Programming to an interface , Not implementation classes
- Multipurpose combination , Use less inheritance
The strategy model consists of three parts :
- Strategy( Strategy )
Defines the common interface for all policies . Context (Context) Use this interface to call a specific policy (ConcreteStrategy). - ConcreteStrategy( Specific strategies )
Strategy Interface implementation , A specific policy implementation is defined . - Context( Context )
Defined Strategy How objects are used , Is the caller of the policy algorithm .

3. Code implementation
We use strategy mode to simulate the duck game above .

3.1 Flight behavior realization
Define the flight behavior interface
public interface Fly {
void fly();
}
Flying with wings to achieve class
public class FlyWithWings implements Fly {
@Override
public void fly() {
System.out.println(" Fly with wings ");
}
}
You can't implement classes
public class FlyNoWay implements Fly {
@Override
public void fly() {
System.out.println(" I can't fly ");
}
}
3.2 The realization of duck calling behavior
Define the duck call behavior interface
public interface Quack {
void quack();
}
Quack implementation class
public class QuackGuaGua implements Quack {
@Override
public void quack() {
System.out.println(" Quack quack ");
}
}
Squeak implementation classes
public class QuackZhiZhi implements Quack {
@Override
public void quack() {
System.out.println(" Squeak ");
}
}
It's not called an implementation class
public class QuackNoWay implements Quack {
@Override
public void quack() {
System.out.println(" Don't call ");
}
}
3.3 Duck class implementation
Define abstract classes
public abstract class Duck {
protected Fly fly;
protected Quack quack;
public void swim() {
System.out.println(" I'm swimming ...");
}
public abstract void display();
public Fly getFly() {
return fly;
}
public Quack getQuack() {
return quack;
}
}
Wild duck implementation class
public class MallardDuck extends Duck {
// Ducks fly on their wings , Quack quack
public MallardDuck() {
this.fly = new FlyWithWings();
this.quack = new QuackGuaGua();
}
@Override
public void display() {
System.out.println(" It looks like a mallard ");
}
}
Red head duck implementation class
public class RedheadDuck extends Duck {
// The red headed duck flies on its wings , Quack quack
public RedheadDuck() {
this.fly = new FlyWithWings();
this.quack = new QuackGuaGua();
}
@Override
public void display() {
System.out.println(" The appearance is red headed duck ");
}
}
Rubber duck implementation class
public class RubberDuck extends Duck {
// Rubber ducks can't fly , Squeak
public RubberDuck() {
this.fly = new FlyNoWay();
this.quack = new QuackZhiZhi();
}
@Override
public void display() {
System.out.println(" It's rubber duck ");
}
}
Bait duck implementation class
public class DecoyDuck extends Duck {
// Bait ducks can't fly , I don't know how to call
public DecoyDuck() {
this.fly = new FlyNoWay();
this.quack = new QuackNoWay();
}
@Override
public void display() {
System.out.println(" The appearance is bait duck ");
}
}
3.4 test
Write simple test classes
public class Test {
public static void main(String[] args) {
MallardDuck mallardDuck = new MallardDuck();
mallardDuck.display();
mallardDuck.swim();
mallardDuck.getFly().fly();
mallardDuck.getQuack().quack();
System.out.println("-------------------");
DecoyDuck decoyDuck = new DecoyDuck();
decoyDuck.display();
decoyDuck.swim();
decoyDuck.getFly().fly();
decoyDuck.getQuack().quack();
}
}
Output results
It looks like a mallard
I'm swimming ...
Fly with wings
Quack quack
-------------------
The appearance is bait duck
I'm swimming ...
I can't fly
Don't call
4. Complete code
Please visit my Github, If it helps you , Welcome to a Star, thank you !
https://github.com/gozhuyinglong/blog-demos/tree/main/design-patterns/src/main/java/io/github/gozhuyinglong/designpatterns/strategy
5. Reference resources
- 《 Head First Design patterns 》
- 《 Design patterns : The foundation of reusable object-oriented software 》
Recommended reading
边栏推荐
- Beaucoup de CTO ont été tués aujourd'hui parce qu'il n'a pas fait d'affaires
- Kubernetes resource object introduction and common commands (V) - (configmap)
- Principles of BTC cryptography
- Apache+php+mysql environment construction is super detailed!!!
- Learn libcef together -- set cookies for your browser
- Transferring images using flask
- How to set up altaro offsite server for replication
- NG Textarea-auto-resize
- [practical project] autonomous web server
- 一起上水碩系列】Day 9
猜你喜欢

中职网络子网划分例题解析

@Autowired 导致空指针报错 解决方式

一起上水碩系列】Day 9

Analysis of the example of network subnet division in secondary vocational school

Altaro virtual machine replication failed: "unsupported file type vmgs"

How to install and configure altaro VM backup for VMware vSphere

Go practice -- design patterns in golang's singleton

Today, many CTOs were killed because they didn't achieve business

Beaucoup de CTO ont été tués aujourd'hui parce qu'il n'a pas fait d'affaires

(subplots usage) Matplotlib how to draw multiple subgraphs (axis field)
随机推荐
Deep embedding and alignment of Google | protein sequences
Jetson AgX Orin platform porting ar0233 gw5200 max9295 camera driver
2022.7.2 simulation match
Learn libcef together -- set cookies for your browser
Redis cannot connect remotely.
Mapbox tasting value cloud animation
Deploy crawl detection network using tensorrt (I)
Notepad++ wrap by specified character
6.23星期四库作业
Introduction to webrtc protocol -- an article to understand dtls, SRTP, srtcp
Export the altaro event log to a text file
Brief introduction of realsense d435i imaging principle
Go practice -- use JWT (JSON web token) in golang
牛客网 JS 分隔符
Progressive multi grasp detection using grasp path for rgbd images
Differences among bio, NiO and AIO
Ansible firewall firewalld setting
kubernetes资源对象介绍及常用命令(五)-(ConfigMap)
今天很多 CTO 都是被幹掉的,因為他沒有成就業務
"250000 a year is just the price of cabbage" has become a thing of the past. The annual salary of AI posts has decreased by 8.9%, and the latest salary report has been released