0% found this document useful (0 votes)
48 views

Strategy Pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows an algorithm to be chosen at runtime. The context uses a strategy interface to call the algorithm without knowing its concrete implementation. Strategies implement the algorithm while encapsulating its details. This decouples an object from how it accomplishes an action, allowing strategies to be easily substituted.

Uploaded by

Đặng Đạt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Strategy Pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows an algorithm to be chosen at runtime. The context uses a strategy interface to call the algorithm without knowing its concrete implementation. Strategies implement the algorithm while encapsulating its details. This decouples an object from how it accomplishes an action, allowing strategies to be easily substituted.

Uploaded by

Đặng Đạt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Strategy Pattern

I. Overview
1. Definition:
- Defines a family of algorithms, encapsulates each one,
and makes them interchangeable. Strategy lets the
algorithm vary independently from clients that use it.
- Capture the abstraction in an interface, bury
implementation details in derived classes.
2. Principles in the pattern:
- Principle 1: Encapsulate what varies (identify the aspects
of the application that vary and separate them from
what stays the same).
- Principle 2: Program to interfaces, not implementations
(by “interface”, this principle isn’t limiting itself to
Java interfaces, it also covers supertypes, preferably
abstract classes or interfaces, both of which refer to
classes with undefined behaviors).
- Principle 3: Favor composition over inheritance.
3. Pros and Cons:
- Advantages:
 Using encapsulation the algorithm separately, new
algorithms complying with the same interface can be
easily introduced.
 The strategy pattern application can switch
strategies at run-time.
 Strategy enables the clients to choose the required
algorithm, without using a "switch" statement or a
series of "if-else" statements.
 Data structures used for implementing the algorithm
is completely encapsulated in Strategy classes.
Therefore, the implementation of an algorithm can
be changed without affecting the Context class.
 The same Strategy object can be strategically shared
between different Context objects. However, the
shared Strategy object should not maintain states
across invocations.
- Disadvantages:
 The application must be aware of all the strategies
to select the right one for the right situation.
 Strategy and Context classes may be tightly coupled.
The Context must supply the relevant data to the
Strategy for implementing the algorithm and
sometimes, all the data passed by the Context may
not be relevant to all the Concrete Strategies.
 The application configures the Context with the
required Strategy object. Therefore, the application
needs to create and maintain two objects in place of
one.
 Since, the Strategy object is created by the
application in most cases; the Context has no control
on lifetime of the Strategy object. However, the
Context can make a local copy of the Strategy object.
But, this increases the memory requirement and has
a sure performance impact.

4. Issues can be resolve by using Strategy Pattern

- Sorting: the requirement is about sorting these numbers,


but it is not clear at the moment that if programmers
should use BrickSort, BubbleSort or some other sorting.

- Validation: the requirement is about checking items


according to "Some rules", but it's not yet clear what that
rule will be, and it can be new ones in the future.

- Updating behaviors: For example, the character in a


game can either walk or run when he moves, but maybe
in the future, when the level is up, he even can fly or
swim.

- Storing information: the application may require to store


information to the Database, but later it may need to be
able to save a file, or make a webcall.

- Outputting: We need to output X as a plain string, but


later may be a CSV, XML, JSON, etc.
II. UML diagrams

Figure 1. Class diagram and Sequence diagram.


- In the above UML class diagram, the Context class
doesn't implement an algorithm directly.
Instead, Context refers to the Strategy interface for
performing an algorithm (strategy.algorithm()), which
makes Context independent of how an algorithm is
implemented. The Strategy1 and Strategy2 classes
implement the Strategy interface, that is, implement
(encapsulate) an algorithm.

- The UML sequence diagram shows the run-time


interactions: The Context object delegates an algorithm
to different Strategy objects
First, Context calls algorithm() on a Strategy1 object,
which performs the algorithm and returns the result
to Context. Thereafter, Context changes its strategy and
calls algorithm() on a Strategy2 object, which performs
the algorithm and returns the result to Context.
III. The Strategy Pattern in Java
1. The requirement
- Creating a demo of payment system, when a bill can be
paid using a variety of payment methods selected at
runtime
2. Class diagram

Figure 2 Class diagram of Payment system


3. Code
- Step 1: Define the strategy interface PaymentMethod as
follows:
- Step 2: Moving to the most simple concrete strategy, we
implement the Cash class as follows:

- Step 3: Since the system is not connected to any real


bank, it will simply print that we have paid for our bill
using cash, which allows users to differentiate between
the various payment methods. To implement the
CreditCard and DebitCard classes, it is necessary to
create an abstract class named Card :
- Step 4: Then creating CreditCard and DebitCard classes as
follows:

And:

- Step 5: Now it is necessary to create a means of selecting


the correct concrete payment strategy, which is the
PaymentMethodFactoy class (note that this class is an
implementation of the Factory Method pattern, which
will be introduced later in the report):
- Step 6: With the strategies implemented, it is the
appropriate time to implement the LineItem and Bill
classes:

And:
- Step 7: Finally, the Application class is created to test all
the code above :
And there are the results for each keyboarInput:
 credit:
Payed 350 cents using credit card[name = John Doe, number = 4111111111111111, CVV = 123,
expiration = 01/22]

 debit:
Payed 350 cents using debit card[name = John Doe, number = 4111111111111111, CVV = 123, e
xpiration = 01/22]

 cash:
Payed 350 cents using cash

IV. Conclusion
- To wrap up, The Strategy Pattern is considered as one of
the most important design pattern due to its huge
benefits l in solving different problems in coding such as:
sorting, validation, outputing etc. Therefore, it is
necessary for every programmer to comprehend and use
the pattern expertly and thereby can improve their
coding capability.

You might also like