<< Chapter < Page Chapter >> Page >

Balls that change their strategies

Let's consider a the notion of a ball that changes its behavior. Since we have modeled a ball as having a strategy, we can simply say that in some manner, it is the ball's strategy that changes. We could say that the ball changes its strategy, but since the ball doesn't know which strategy it has to begin with, it really doesn't know one strategy from another. One could argue that it therefore can't know when or if it should ever change its strategy. Therefore, the ball cannot be coded to change its own strategy! So, whose baliwick is the changing of the strategy?

Since the changing of a strategy is a strategy for updating the ball, it is the strategy that determines the change. The strategy changes the strategy! Let's consider the following strategy: package ballworld; import java.awt.*;public class Change1Strategy implements IUpdateStrategy { private int i = 500; // initial value for ipublic void updateState(Ball context) {if(i==0) context.setStrategy(new CurveStrategy()); // change strategy if i reaches zero else i--; // not yet zero, so decrement i} } This strategy acts just like a StraightStrategy for 500 updates and then it tells the ball (its context ) to switch to a CurveStrategy . Once the CurveStrategy is installed, the ball becomes curving, without the need for any sort of conditionals to decide what it should do. The context ball fundamentally and permanently becomes curving.

What would happen if you had two strategies like the one above, but instead of replacing themselves with CurveStrategy 's , they instead instantiated each other?

Try it!

Got questions? Get instant answers now!

A key notion above is that a strategy can contain another strategy. In the above example, the Change1Strategy could have easily pre-instantiated the CurveStrategy and saved it in a field for use when it was needed. But the does it matter exactly which concrete strategy is being used? If not, why not work at a higher abstraction level and let one strategy hold a reference to an abstract strategy? For instance, consider the following code: package ballworld; import java.awt.*;public class SwitcherStrategy implements IUpdateStrategy {private IUpdateStrategy _strategy = new StraightStrategy();public void updateState(Ball context) { _strategy.updateState(context);}public void setStrategy(IUpdateStrategy newStrategy) { _strategy = newStrategy;} } This strategy doesn't look like it does much, but looks are deceiving. All the SwitcherStrategy does is to delegate the updateState method to the _strategy that it holds. This does not seem much in of itself, but consider the fact that the SwitcherStrategy also has a settor method for _strategy . This means that the strategy held can be changed at run time! More importantly, suppose a ball is instantiated with a SwitcherStrategy . The behavior of the ball would be that of whatever strategy is being held by the SwitcherStrategy since the switcher just delegates to the held strategy. If one were to have a reference to that SwitcherStrategy instance from somewhere else, one could then change the internal strategy. The ball is none the wiser because all it has is a reference to the SwitcherStrategy instance, which hasn't changed at all! However, since the held strategy is now different, the ball's behavior has completely changed! This is an example of the Decorator Design Pattern , where the SwitcherStrategy class is formally called the decorator and the held strategy is formally called the decoree . In theoretical terms, the decorator is what is known as an indirection layer , which is like a buffer between two enities that enables them to depend on each other but yet still be free to move and change with respect to each other. A very useful analogy for indirection layers is like the thin layer of oil that will enable two sheets of metal to slide easily past each other.

Balls with multiple, composite behaviors

Now that we can dynamically change a ball's behavior, let's tackle another problem:

How can we have balls with multiple behaviors but yet not duplicate code for each one of those behaviors?

Use the same techniques as before: strategies that hold strategies.

Got questions? Get instant answers now!
Let's start with a very straightforward solution: package ballworld; import java.awt.*;public class DoubleStrategy implements IUpdateStrategy {private IUpdateStrategy _s1 = new CurveStrategy(); private IUpdateStrategy _s2 = new BreathingStrategy();public void updateState(Ball context) {_s1.updateState(context); _s2.updateState(context);} } Ta da! No problem. The DoubleStrategy simply holds two strategies and delegates to each of them in turn when asked to updateState . So why stop here? package ballworld; import java.awt.*;public class TripleStrategy implements IUpdateStrategy {private IUpdateStrategy _s1 = new CurveStrategy(); private IUpdateStrategy _s2 = new BreathingStrategy();private IUpdateStrategy _s3 = new BreathingStrategy();public void updateState(Ball context) { _s1.updateState(context);_s2.updateState(context); _s3.updateState(context);} } We're on a roll now! We could go on and on, making as complex a strategy as we'd like, making a new class for each combination we want. But somewhere around the 439'th combination, we get mightly tired of writing classes. Isn't there an easier way?

Abstraction is the key here. We want to write code that represents that abstraction of multiple, composite strategies. Does what we were doing above depend on the particular concrete strategies that we were using? No? Then we should eliminate the concrete classes, raise the abstraction level and use the abstract superclass (interface) instead. For a combination of two behaviors, we end up with the following: package ballworld; import java.awt.*;public class MultiStrategy implements IUpdateStrategy { private IUpdateStrategy _s1;private IUpdateStrategy _s2; public MultiStrategy(IUpdateStrategy s1, IUpdateStrategy s2) {_s1 = s1; _s2 = s2;}public void updateState(Ball context) { _s1.updateState(context);_s2.updateState(context); }} Notice how we have added a constructor that enables us to initialize the two abstract strategy fields. All we have to do is to construct a MultiStrategy object with the two desired strategies, and we're good to go!

So if we want three behaviors, all we have to do is to make the same sort of thing but with 3 abstract strategy fields, right?

But isn't a MultiStrategy an IUpdateStrategy iteself? That is, since a MultiStrategy holds IUpdateStrategy 's, couldn't a Multistrategy hold a Multistrategy , which is holding a Multistrategy (or two) which is hold a Multistrategy , which is holding.....?

Got questions? Get instant answers now!
Thus, with just a Multistrategy we are capable of composing arbitrarily complex behaviors!

Composite patterns

So what have we wrought here? Let's take a look at the UML diagram of our to most abstract strategies.

Switcherstrategy and multistrategy

Note that the subclasses hold references to their own superclasses!

The key to the power that lies in the SwitcherStrategy and the MultiStrategy lies in the fact that they hold references to their own superclass, IUpdateStrategy . This is what enables them to be create any behavior they want, including combinations of behaviors and dynamic modifications of behaviors. This self-referential class structure is known as the Composite Design Pattern (The Decorator pattern can be considered to be specialized form of the Composite pattern). The massive power, flexibility and extensiblility that this pattern generates warrants further, more formal study, which is where we're heading next. Stay tuned!

Questions & Answers

differentiate between demand and supply giving examples
Lambiv Reply
differentiated between demand and supply using examples
Lambiv
what is labour ?
Lambiv
how will I do?
Venny Reply
how is the graph works?I don't fully understand
Rezat Reply
information
Eliyee
devaluation
Eliyee
t
WARKISA
hi guys good evening to all
Lambiv
multiple choice question
Aster Reply
appreciation
Eliyee
explain perfect market
Lindiwe Reply
In economics, a perfect market refers to a theoretical construct where all participants have perfect information, goods are homogenous, there are no barriers to entry or exit, and prices are determined solely by supply and demand. It's an idealized model used for analysis,
Ezea
What is ceteris paribus?
Shukri Reply
other things being equal
AI-Robot
When MP₁ becomes negative, TP start to decline. Extuples Suppose that the short-run production function of certain cut-flower firm is given by: Q=4KL-0.6K2 - 0.112 • Where is quantity of cut flower produced, I is labour input and K is fixed capital input (K-5). Determine the average product of lab
Kelo
Extuples Suppose that the short-run production function of certain cut-flower firm is given by: Q=4KL-0.6K2 - 0.112 • Where is quantity of cut flower produced, I is labour input and K is fixed capital input (K-5). Determine the average product of labour (APL) and marginal product of labour (MPL)
Kelo
yes,thank you
Shukri
Can I ask you other question?
Shukri
what is monopoly mean?
Habtamu Reply
What is different between quantity demand and demand?
Shukri Reply
Quantity demanded refers to the specific amount of a good or service that consumers are willing and able to purchase at a give price and within a specific time period. Demand, on the other hand, is a broader concept that encompasses the entire relationship between price and quantity demanded
Ezea
ok
Shukri
how do you save a country economic situation when it's falling apart
Lilia Reply
what is the difference between economic growth and development
Fiker Reply
Economic growth as an increase in the production and consumption of goods and services within an economy.but Economic development as a broader concept that encompasses not only economic growth but also social & human well being.
Shukri
production function means
Jabir
What do you think is more important to focus on when considering inequality ?
Abdisa Reply
any question about economics?
Awais Reply
sir...I just want to ask one question... Define the term contract curve? if you are free please help me to find this answer 🙏
Asui
it is a curve that we get after connecting the pareto optimal combinations of two consumers after their mutually beneficial trade offs
Awais
thank you so much 👍 sir
Asui
In economics, the contract curve refers to the set of points in an Edgeworth box diagram where both parties involved in a trade cannot be made better off without making one of them worse off. It represents the Pareto efficient allocations of goods between two individuals or entities, where neither p
Cornelius
In economics, the contract curve refers to the set of points in an Edgeworth box diagram where both parties involved in a trade cannot be made better off without making one of them worse off. It represents the Pareto efficient allocations of goods between two individuals or entities,
Cornelius
Suppose a consumer consuming two commodities X and Y has The following utility function u=X0.4 Y0.6. If the price of the X and Y are 2 and 3 respectively and income Constraint is birr 50. A,Calculate quantities of x and y which maximize utility. B,Calculate value of Lagrange multiplier. C,Calculate quantities of X and Y consumed with a given price. D,alculate optimum level of output .
Feyisa Reply
Answer
Feyisa
c
Jabir
the market for lemon has 10 potential consumers, each having an individual demand curve p=101-10Qi, where p is price in dollar's per cup and Qi is the number of cups demanded per week by the i th consumer.Find the market demand curve using algebra. Draw an individual demand curve and the market dema
Gsbwnw Reply
suppose the production function is given by ( L, K)=L¼K¾.assuming capital is fixed find APL and MPL. consider the following short run production function:Q=6L²-0.4L³ a) find the value of L that maximizes output b)find the value of L that maximizes marginal product
Abdureman
types of unemployment
Yomi Reply
What is the difference between perfect competition and monopolistic competition?
Mohammed
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Principles of object-oriented programming. OpenStax CNX. May 10, 2013 Download for free at http://legacy.cnx.org/content/col10213/1.37
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Principles of object-oriented programming' conversation and receive update notifications?

Ask