当前位置:网站首页>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
边栏推荐
- Go practice -- factory mode of design patterns in golang (simple factory, factory method, abstract factory)
- mapbox尝鲜值之云图动画
- redis 无法远程连接问题。
- Webrtc native M96 version opening trip -- a reading code download and compilation (Ninja GN depot_tools)
- 在PyCharm中配置使用Anaconda环境
- Go practice -- design patterns in golang's singleton
- Deep embedding and alignment of Google | protein sequences
- Mapbox tasting value cloud animation
- Deploy crawl detection network using tensorrt (I)
- MySQL startup error: several solutions to the server quit without updating PID file
猜你喜欢
ES7 easy mistakes in index creation
@Solutions to null pointer error caused by Autowired
谷歌 | 蛋白序列的深度嵌入和比对
redis 无法远程连接问题。
"C and pointer" - Chapter 13 advanced pointer int * (* (* (*f) () [6]) ()
Why is go language particularly popular in China
6.23 warehouse operation on Thursday
@Autowired 导致空指针报错 解决方式
大二困局(复盘)
Beaucoup de CTO ont été tués aujourd'hui parce qu'il n'a pas fait d'affaires
随机推荐
SimpleITK学习笔记
Xaml gradient issue in uwp for some devices
2022.7.2day594
Go practice -- design patterns in golang's singleton
Apache+PHP+MySQL环境搭建超详细!!!
redis 无法远程连接问题。
Deploy crawl detection network using tensorrt (I)
Webrtc M96 release notes (SDP abolishes Plan B and supports opus red redundant coding)
Together, Shangshui Shuo series] day 9
【一起上水硕系列】Day 10
DEX net 2.0 for crawl detection
Simpleitk learning notes
今天很多 CTO 都是被幹掉的,因為他沒有成就業務
Go practice -- gorilla / websocket used by gorilla web Toolkit
[practical project] autonomous web server
期末复习(Day5)
Final review (Day6)
一起上水碩系列】Day 9
AtCoder Beginner Contest 258(A-D)
Deep embedding and alignment of Google | protein sequences