Clarification Required - Design Patterns

Most design pattern concepts have mentioned that "Has A" is better than "Is A".

In the first chapter - Basic Design Templates - "Introduction to Design Patterns", section "Integrating Duck Behavior" (page No. 15), the Duck class has links to FlyBehavior and QuackBehavior interface types. For example, we will add a new behavior to the function name, which is XYZBehavior (just suppose the client has not solved it yet) for one kind of Ducks, we need to change the Duck class to have a link to the new interface. As a result, we must change the class, but which should not happen according to a good design pattern.

Can you suggest me how we can deal with this requirement?

+3
source share
3 answers

The strategy template does not prevent you from changing the class if you add new behavior (strategy). It simply prevents touching the class if the existing behavior (strategy) changes .

QuackBehaviour: , , "quaack", , "quaaack". , QuackBehaviour QuackBehaviour . .

SwimBehaviour, , - , ( Duck).

, !

0

Injection Dependency

( Java Spring Guice)

, :

private Collection<Behavior> behaviors;
public void setBehaviors(Collection<Behavior> behaviors){
    this.behaviors = behaviors;
}

, Bird.

+1

You can handle this script using Composition=> Duckhas a list Behaviours.

Duckwill maintain a list of Behavior objects. Fill in the appropriate actions when creating the object Duck.

Code example:

import java.util.*;

interface Behaviour{

}
class FlyBehaviour implements Behaviour{

}
class QuackBehaviour implements Behaviour{

}
class XYZBehaviour implements Behaviour{

}

public class Duck{
    private List<Behaviour> duckBehaviours = new ArrayList<Behaviour>();

    public Duck(List<Behaviour> list){
        duckBehaviours = list;
    }
    public static void main(String[] args){
        // set the behaviours
        List<Behaviour> list = new ArrayList<Behaviour>();
        list.add(new FlyBehaviour());
        list.add(new QuackBehaviour());
        list.add(new XYZBehaviour());
        Duck duck = new Duck(list);
    }   
}
0
source

Source: https://habr.com/ru/post/1773811/


All Articles