策略设计模式 Strategy Design Pattern

xiaoxiao2021-02-28  139

1. 策略设计模式初衷

减少代码冗余,降低代码之间的耦合度。同时保证代码的可维护性。 Positive: - Often reduces long lists of conditions - Avoid duplicate code - Keep class changes from other class changes - Can hide complicated/ secret code from the user Negative: Increased number of Objects/Classes

2. 策略实际模式应用场景

当我们想要定义一组算法,而且这些算法所要表现的的内容很相似时。如果在每个父类定义该算法的普适版本,然后在子类中覆盖override该方法这样一方面增加了代码的冗余度,另一方面违背了子类方法应该相互之间不同这一设计原则。但我们想要动态改变对象的某种行为,且该行为有几种可供选择项时。

3. 具体UML图及解释

这里的Animal作为一个base class, derived class–包括Dog和Bird可以直接继承该父类,完成相应的功能,但这不是好的设计准则。因为这样引入了大量冗余代码,且违背了OOD的封装特性。

4. 一个具体的demo

package com.fqyuan.strategy; public interface Flys { public String fly(); } class FlyFast implements Flys { @Override public String fly() { return "Flying fast!"; } } class FlySlow implements Flys { @Override public String fly() { return "Flying slowly!"; } } class NotFly implements Flys { @Override public String fly() { return "Unable to fly!"; } } package com.fqyuan.strategy; public class Animal { private String name; public Flys flyType; public void setName(String name) { this.name = name; } public String getName() { return name; } // The super class pushes off the responsibility for flying to flyType, an // interface instance public String tryToFly() { return flyType.fly(); } // We can add the method to change the Flys type dynamically public void setFlyType(Flys newFlyType) { flyType = newFlyType; } @Override public String toString() { return name; } /* * Bad, you don't want to add methods to the super class. You need to * separate what is different from subclass and the super class. */ // public void fly(){ // System.out.println("I'm flying!"); // } } package com.fqyuan.strategy; public class Dog extends Animal { public Dog(String name) { this.setName(name); /* * We set the interface polymorphically. Here we set the dog disability * to fly. */ flyType = new NotFly(); } /* * Bad! You can override the fly() method, but we're breaking the rule that * we need to abstract what is different to the subclasses. * 即:子类的方法尽量保持一般是和其他子类方法不同,这样可以减少代码的冗余度。 */ // public void fly() { // System.out.println("I can't fly!"); // } } package com.fqyuan.strategy; public class Cat extends Animal { public Cat(String name) { setName(name); this.flyType = new FlyFast(); } } package com.fqyuan.strategy; /* * 设计模式出现的缘由? * 代码的可读性,可维护性,减少代码的冗余度. * 2条重要原则: * 1). 能使用composition的尽量不要用inheritance. * 2). 能使用Interface的尽量不要用具体的class. */ public class StrategyDemo { public static void main(String[] args) { Animal dog = new Dog("Rick"); Cat cat = new Cat("Kitty"); System.out.println(dog + " " + dog.tryToFly()); System.out.println(cat + " " + cat.tryToFly()); dog.setFlyType(new FlySlow()); System.out.println(dog + " " + dog.tryToFly()); } } //Running result: Rick Unable to fly! Kitty Flying fast! Rick Flying slowly!
转载请注明原文地址: https://www.6miu.com/read-62596.html

最新回复(0)