java - How to modify a pre-defined package methods outside of the package? -


Suppose I have a package called 'animal' with animal origin, expanses from cat animal, extends from dog animals . The animal, however, is designed like this:

  class animal {int amount; Next animal; // Then a constructor starts these initiatives. Drinker (int n) {...}}  

cat & amp; Dog classes follow this structure:

  Expands square cat {cat (int, animal next) {super (volume, next); } @ Override Drinking Water (Int N) {..}}  

Each of them is method, drinker () like this:

  public zero Drink water (int n) {zodiac - = n; If (amount & lt; 0) amount = 0; If (next! = Null) next.drinkWater (n); }  

What I am trying to do here, I have created a 'linked list' of animals, each of them in order to drink drinking water in order. Suppose, however, that if a cat drinks the amount of water, its volume decreases by the amount of N + 1.

My objective is to find a solution to overcome this problem which 'original animal package, but changes in drinking water behavior, each one of them' Come along:

  class InvokeStaticTypeBDrink {static zero type Brdrink (animal animal, int n) {animal.amount - = n; If (animal number & lt; 0) animal.amount = 0; If (animal.next! = Null) {If (animal instision cat) invokeStaticTypeDrink.drinkWater (animal.next, n + 1); And if (animal example dogs) InvokeStaticTypeDrink.drinkWater (animal.next, n-1); Other invococathetic type drank. Drill water (animal nXT, n); }}}  

Again, I started researching. Because it actually sees quick and dirty solutions.

So, I found that a design pattern called 'Visitor Pattern'. Well, a very good pattern that solves the problem with a duplicate dispatch, but there is a problem on my side: Visual Interface (which accepts () method should be 'implemented' by the original animal However, my goal is' original animal There is no modification on the package, but changing the behavior of drinking water '. I am pretty sure that I am missing something.

So, do you think that a little hack, Visitor Petter Will not work still or will any other pattern / solution be better? Thank you.

If you use basic classes If you do not want to touch, then the only way to implement visitor pattern is to wrap the original sections into new (wrap) classes.

However, if you want to change the behavior of some animals, then In your situation, I just increase those strong sections and drink behavior Override .

Then you will have a cat like this:

  class non-thirsty cat cat {cat (int amount, next animal) {super (Amount, next); } @ Override Public Voice Drink Water (Int N) {Zodiac + = N; If (amount & lt; 0) amount = 0; If (next! = Null) next.drinkWater (n); }}  

Comments