Sie sind auf Seite 1von 33

ASSIGNMENT 1 FRONT SHEET

Qualification BTEC Level 5 HND Diploma in Computing

Unit number and title Unit 19: Data Structures & Algorithms

Submission date Date Received 1st submission

Re-submission Date Date Received 2nd submission

Nguyễn Ngoc Tài


Student Name Student ID GC17114
Nguyễn Viết Quốc Khánh

Class GCD0605 Assessor name Hoang Nhu Vinh

Student declaration

I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand that
making a false declaration is a form of malpractice.

Student’s signature

Grading grid

P1 P2 P3 M1 M2 M3 D1 D2
r Summative Feedback: r Resubmission Feedback:

Grade: Assessor Signature: Date:


Internal Verifier’s Comments:

Signature & Date:


Table of Contents
I. Introduction. ................................................................................................................................. 5
II. P1&M1 Examine the characteristics of the object-orientated paradigm as well as the various
class relationships................................................................................................................................. 6
1. Abstraction ................................................................................................................................................. 6
2.Encapsulation .............................................................................................................................................. 8
3.Inheritance ................................................................................................................................................. 11
4.Polymorphism ............................................................................................................................................ 12
III. P2&M2 Determine a design pattern from each of the creational, structural and behavioural pattern
types .............................................................................................................................................................. 15
1. Definition : ................................................................................................................................................ 15
2. Why use Design Patterns? ........................................................................................................................ 15
3. Classification Design Patterns : ................................................................................................................ 15
3.1 Creational Pattern : ................................................................................................................................ 16
a ) Definition : .....................................................................................................................................................................16
b) Why use it? ......................................................................................................................................................................17
c) How to use it with source code demonstration ...............................................................................................................17

3.2. Structural Pattern :................................................................................................................................ 22


a) Definition .........................................................................................................................................................................22
b) Why use it? ......................................................................................................................................................................23
c) How to use it with source code demonstration ...............................................................................................................23

3.3 Behavioral Pattern : ................................................................................................................................ 28


a) Definition : ......................................................................................................................................................................28
b) Why use it? ......................................................................................................................................................................29
c) How to use it with source code demonstration: ..............................................................................................................30

Bibliography ....................................................................................................................................... 33
Table of Figures.
Figure 1: Abstraction .................................................................................................................................................... 6
Figure 2: Abstraction .................................................................................................................................................... 7
Figure 3: Abstraction Result.......................................................................................................................................... 7
Figure 4: Abstraction class diagram .............................................................................................................................. 8
Figure 5: Encapsulation source code. ........................................................................................................................... 9
Figure 6: Encapsulation source code. ......................................................................................................................... 10
Figure 7: Encapsulation class diagram. ....................................................................................................................... 10
Figure 8: Inheritance source code. ............................................................................................................................. 11
Figure 9: Inheritance class diagram. ........................................................................................................................... 11
Figure 10: Polymorphism source code. ...................................................................................................................... 12
Figure 11: Polymorphism Result. ................................................................................................................................ 12
Figure 12: Polymorphism source code. ...................................................................................................................... 13
Figure 13: Polymorphism result. ................................................................................................................................. 13
Figure 14: Polymorphism class diagram. .................................................................................................................... 14
Figure 15: buidler pattern diagram............................................................................................................................. 16
Figure 16: buidler pattern class diagram. ................................................................................................................... 18
Figure 17: Result. ........................................................................................................................................................ 21
Figure 18: Flywiegh Class diagram. ............................................................................................................................. 22
Figure 19: Flywiegh class diagram. ............................................................................................................................. 24
Figure 20: Result. ........................................................................................................................................................ 27
Figure 21: Stragery class diagram. .............................................................................................................................. 29
Figure 22: Stragery class diagram. .............................................................................................................................. 30
Figure 23: Stragery result........................................................................................................................................... 32
I. Introduction.
- You and your team need to explain the characteristics of an object-oriented programming model by
applying object-oriented analysis and design on a (hypothetical) scenario. The script may be small but
can show the various characteristics of OOP (such as: encapsulation, inheritance, polymorphism,
override, overload, etc.).
- The second task is to introduce a number of designs (including 3 types: creativity, structure and
behavior) to the audience by giving real case scenarios, the corresponding patterns are illustrated by
UML class diagram.
- To summarize, you should analyze the relationship between object-oriented models and design
patterns.
II. P1&M1 Examine the characteristics of the object-orientated paradigm as well as the various
class relationships.

Object-oriented is a process of using class to showcase each different functional areas or objects of data in
a software application. The data objects contained in its data fields (attributes), and the method used to
define the manipulation with data. (Hieu, 2017)
There are some characteristics :

1. Abstraction
Abstraction is the concealment of internal details and displays functions such as attributes, methods of an
object for other classes can use. In other words, abstraction is giving out the underlying information of
objects in the real world and hides the whole details of an object.
Example :

Figure 1: Abstraction
In the above example, I created 3 object classes which are Animal, Dog and Cat, where Animal class is
abstract class. The animal class has an abstract method called Action () and Introduction () which is used to
display the action and introduce each corresponding animal. Because it is abstract, every method in the
Animal class is required to appear in the inherited classes of Dog and Cat classes, and we can change the
value in that method by overriding it. In addition, in the two classes Dog and Cat, although using the same
method from the Animal class, the declaration inside their methods is different, so it clearly shows the
abstract in each class. In particular, Class Animal is an abstract class, so it can not initialize objects like
normal classes. It is just a rib, so that we can create subclasses based on the binding from this rib, which is
Class Dog and Class Cat. This makes maintenance easier. The image below is the Main function we built
from the image above.

Figure 2: Abstraction

The image below is the result of the above example :

Figure 3: Abstraction Result.


UML for abstraction :

Figure 4: Abstraction class diagram

2.Encapsulation
Demonstrates the scope of use of classes, methods, and properties. These ranges are represented by access
modifiers: puplic, protected, private. (which ensures the integrity and security of the object).

The image below is the access level of each Access Modifier included in OOP
Example :

Figure 5: Encapsulation source code.

In the Dog class, we wanted the Age field to be accessible within this class so we used private as the access
modifer for this Age field. This makes it inaccessible outside the scope of the Dog class and if you want to
access Dog outside the program, there must be an intermediary wall that is the public Age variable. In the
Animal class, we want the name field to be accessed only within the scope of that class and also to the
derived class, so we use protected as the access modifer for this name field. Therefore, in the Dog class that
inherits the Animal class, it is still possible to use this field to declare the name for this object. In addition,
the Age field is used privately as an access modifer, so even though Dog class inherits Animal class, it still
cannot access it.

In the Dog class, the GetAge () and GetName () methods use the public as an access modifer, so its access
scope may be outside the scope of the class. The image below illustrates an object via the main function.
Figure 6: Encapsulation source code.

In the main function, when initializing a Dog object, we can access methods using public easily and private
and protected cannot be accessed because it has been limited in scope.
UML for encapsulation:

Figure 7: Encapsulation class diagram.


3.Inheritance
Allow build a new class based on the definition of a class available. The new class was created can reuse
code by inheriting all elements of the original class and it can extend inheritance elements or add new
components.
Example :

Figure 8: Inheritance source code.

In the image above, the Cat class inherits the Animal class so all properties and fields in the Animal class
will be included in the Dog class. Therefore, in the Act () method, the age value in the Animal class will be
given and the Dog class to declare, so when the Main function is launched, the Act () method declaration
will give the value of the age wall in the Animal class even though it is printed in Dog class.
UML for Inheritance

Figure 9: Inheritance class diagram.


4.Polymorphism
Polymorphism is the feature that whereby objects of different classes can understand the same information
of another class by different ways.
Example :

Figure 10: Polymorphism source code.

In the Dog class, we use the address() method to declare the address for the object, but we want each object
to be declared with a different number of input variables. Therefore, for each address method, we declare
2-3 input variables for them and when giving the main function to run, they have the following result.

Figure 11: Polymorphism Result.


From the image above, we see that each object can use the same name method with different input values
and that is the overloading method. Therefore, using overloading will be very helpful for initializing
methods of the same name but with different actions.

Figure 12: Polymorphism source code.

In the Animal class, we use the Eat () method, and also in the Dog class, we don't want to record the content
of the Eat () method in the Animal class so we used the override method to override it. The content contained
in this method in the Animal class is different from the content in the Dog class. The program after executing
the override is executed as follows.

Figure 13: Polymorphism result.


As seen, the above line is printed by inheriting the Eat () method found in the Animal class and the second
line overrides the content of this method contained in the Dog class. Therefore, an object can use the method
of the superclass and can also change its contents by overriding.

UML for Polymorphism :

Figure 14: Polymorphism class diagram.


III. P2&M2 Determine a design pattern from each of the creational, structural and behavioural
pattern types
1. Definition :
- Design patterns are solutions that have been optimized and reused for the programming problems we
encounter every day. It is a model that has been thought and resolved in a particular situation.

- The problems you encounter may come up with a solution yourself, but it may not be optimal. Design
Pattern helps you solve problems in the most optimal way, providing you with solutions in OOP
programming. It is not a specific language at all. Design patterns are possible in most programming
languages. We often encounter it in OOP programming. (Giang, 2019)

2. Why use Design Patterns?


- Design Pattern helps you to reuse code and extend it easily.

- It is a collection of more optimized, proven solutions to solve problems in software engineering. So when
you encounter any difficulties, design patterns are a guide to help you solve a problem instead of finding a
solution for a proven problem yourself.

- The design pattern provides a solution in general form, which helps speed up software development by
introducing test and development models that have been tested.

- Reusing design patterns helps avoid potential problems that can cause major errors, and are easy to upgrade
and maintain later.

- Help programmers understand the code of others quickly (can be interpreted as communicating). All team
members can easily exchange with each other to build projects without taking too much time.

3. Classification Design Patterns :


There are 3 main groups:

• Creational Pattern (creation group) includes: Abstract Factory, Factory Method, Singleton,
Builder, Prototype. It will help you in object creation, as you know to create you must use the new
keyword, the Creational Pattern team will use some tricks to initialize the object that you will not
see this keyword.
• Structural Pattern (structure group) includes: Adapter, Bridge, Composite, Decorator, Facade,
Proxy and Flyweight. It is used to establish and define relationships between objects.
• Behavioral Pattern includes: Interpreter, Template Method, Chain of Responsibility, Command,
Iterator, Mediator, Memento, Observer, State, Strategy and Visitor. This group is used in the
implementation of object behaviors.
3.1 Creational Pattern :
a ) Definition :
- Creational pattern aim to separate a system from the way its objects are created, composed and performed.
They increase the flexibility of the system about what, who, how and when to create objects.

- Creational pattern include both of the following:

• Abstract Factory: Create an instance of some family of classes


• Builder: Separate building object from its representation
• Factory Method: Create an instance of several derived classes
• Prototype: A fully initialized version will be copied or cloned
• Singleton: A class exists only a single instance

- There are many design patterns in the creational pattern, but we have chosen one to explain and draw
diagrams to illustrate them and explain why they are used.

- The sample we chose to draw and illustrate is a buidler.

• Definition: Separate the construction of a complex object from its representation so that the same
construction process can create different representations. (Khanh, 2019)

Figure 15: buidler pattern diagram.


- The classes and objects participating in this pattern are:

+ Builder : specify the abstract interface to create parts of the Product object

+ ConcreteBuilder

• Build and assemble product parts by deploying the Builder interface


• Define and track the representation it creates
• Provide an interface for product traceability

+ Director : constructs an object using the Builder interface

+ Product :

• Representing complex objects is under construction. ConcreteBuilder builds the internal


representation of the product and determines the process by which it is assembled
• Including classes that define component parts, including interfaces to assemble parts into end
results

b) Why use it?


We should use the swim builder pattern for the benefits it brings below:

- The Builder design pattern helps us cut the operations of building an object. It focuses on building a
complex object step by step. It also implements a process to create an object as a finished product. That
means an object must be massaged by a number of guided steps before it is ready and can be used by
others.

- In general, it allows you to encapsulate complex creation logic. Suppose we are developing a solution to
build a large soccer field in different seasons according to the application user's choice. We will create a
constructor class and pass season information object in the constructor class. After that, the construction
class is responsible for building a seasonal school.

- The construction model is very similar to the factory model. The main difference between builders and
factories is that builders are useful when you need to do a lot of work to build an object.

c) How to use it with source code demonstration


We will use the Builder Patten as an example to demonstrate the following:

There is a laptop manufacturing company that specializes in producing two types of laptops as follows:

• Gaming laptop
• Normal laptop

Because the features of the two laptops are different, the built-in accessories in both laptops are different,
so the way it is built will be required to produce these laptops.
Here, we will create the objects of normal gaming and laptop computers using the build designs in C #.

Class Diagram

Figure 16: buidler pattern class diagram.

Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Builder
{
// 'Product' class
class Laptop
{
public string ModelNumber { get; set; }
public string Display { get; set; }
public string RAM { get; set; }
public string GraphicsCard { get; set; }
public string TouchScreen { get; set; }

public void PrintDetails()


{
Console.WriteLine("----------- Laptop Details ----------------");
Console.WriteLine("Model Number: {0}", ModelNumber);
Console.WriteLine("Display: {0}", Display);
Console.WriteLine("RAM: {0}", RAM);
Console.WriteLine("Graphics Card: {0}", GraphicsCard);
Console.WriteLine("Touch Screen: {0}", TouchScreen);
}
}
// 'Builder' interface
interface ILaptopBuilder
{
void addModelNumber();
void addDisplay();
void addRAM();
void addGraphicsCard();
void addTouchScreen();

Laptop getLaptop();
}
// 'ConcreteBuilder' class - implements 'Builder' interface
class GamingLaptopBuilder : ILaptopBuilder
{
Laptop laptop = new Laptop();
public void addModelNumber()
{
laptop.ModelNumber = "Gaming1001";
}
public void addDisplay()
{
laptop.Display = "Full HD display";
}
public void addRAM()
{
laptop.RAM = "16 GB";
}
public void addGraphicsCard()
{
laptop.GraphicsCard = "Nvidia GeForce";
}
public void addTouchScreen()
{
laptop.TouchScreen = "Yes";
}
public Laptop getLaptop()
{
return laptop;
}
}
// 'ConcreteBuilder' class - implements 'Builder' interface
class NormalLaptopBuilder : ILaptopBuilder
{
Laptop laptop = new Laptop();
public void addModelNumber()
{
laptop.ModelNumber = "Normal1001";
}
public void addDisplay()
{
laptop.Display = "SD Display";
}
public void addRAM()
{
laptop.RAM = "2GB";
}
public void addGraphicsCard()
{
laptop.GraphicsCard = "No graphics card";
}
public void addTouchScreen()
{
laptop.TouchScreen = "NO";
}
public Laptop getLaptop()
{
return laptop;
}
}
// 'Director' class
class LaptopManufacturer
{
public void BuildLaptop(ILaptopBuilder laptopBuilder)
{
laptopBuilder.addModelNumber();
laptopBuilder.addDisplay();
laptopBuilder.addRAM();
laptopBuilder.addGraphicsCard();
laptopBuilder.addTouchScreen();
}
}

class Program
{
static void Main(string[] args)
{
// create object of manufacturer
LaptopManufacturer laptopManufacturer = new LaptopManufacturer();
// build Gaming Laptop
ILaptopBuilder gamingLaptopBuilder = new GamingLaptopBuilder();
laptopManufacturer.BuildLaptop(gamingLaptopBuilder);
Laptop GamingLaptop = gamingLaptopBuilder.getLaptop();
// print details
Console.WriteLine("Gaming Laptop Object:");
GamingLaptop.PrintDetails();

// build normal laptop


ILaptopBuilder normalLaptopBuilder = new NormalLaptopBuilder();
laptopManufacturer.BuildLaptop(normalLaptopBuilder);
Laptop NormalLaptop = normalLaptopBuilder.getLaptop();
// print details
Console.WriteLine("\nNormal Laptop Object:");
NormalLaptop.PrintDetails();

Console.ReadLine();
}
}
}
After executing with the c # code is complete. We run the program and the results are printed as the image below

Figure 17: Result.


3.2. Structural Pattern :
a) Definition
In software engineering, structural design patterns are designs that make it easy to design by simply
identifying a relationship between entities.

- Structural pattern include both of the following:

• Adapter: Match interfaces of different classes


• Bridge: Separates an object’s interface from its implementation
• Composite: A tree structure of simple and composite objects
• Decorator: Add responsibilities to objects dynamically
• Facade: A single class that represents an entire subsystem
• Flyweight : A fine-grained instance used for efficient sharing
• Proxy: An object representing another object

- There are many design patterns in the Structural pattern, but we have chosen one to explain and draw
diagrams to illustrate them and explain why they are used.

- The sample we chose to draw and illustrate is a Flywiegh.

• Definition: In computer programming, fly weight is a software design pattern. A weight is an object
that minimizes memory usage by sharing as much data as possible with other similar objects; It's a
way to use objects in large numbers when a simple repetitive representation will use an unacceptable
amount of memory. (NONE, không ngày tháng)

Figure 18: Flywiegh Class diagram.


- The classes and objects participating in this pattern are:

+ Flyweight : declares an interface through which flyweights can receive and act on extrinsic state.

+ ConcreteFlyweight : implements the Flyweight interface and adds storage for intrinsic state, if any. A
ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic, that is, it must be
independent of the ConcreteFlyweight object's context.

+ UnsharedConcreteFlyweight : not all Flyweight subclasses need to be shared. The Flyweight interface
enables sharing, but it doesn't enforce it. It is common for UnsharedConcreteFlyweight objects to have
ConcreteFlyweight objects as children at some level in the flyweight object structure

+ FlyweightFactory :

• Creates and manages flyweight objects


• Ensures that flyweight are shared properly. When a client requests a flyweight, the FlyweightFactory
objects assets an existing instance or creates one, if none exists.

+ Client :

• Maintains a reference to flyweight


• Computes or stores the extrinsic state of flyweight

b) Why use it?


- We should use the flyweigh pattern because of some of the benefits it brings as follows:

• Requires a large number of objects in some applications or products.


• Storage costs are high and it is difficult to maintain the number of objects.
• Regardless of the object's identity.
• Reduce the number of Entities to handle.
• Reduce memory and on storage devices, if the object still exists

c) How to use it with source code demonstration


- A game application includes a lot of Solider (soldiers), divided into categories: Yuri, Spy, Doctor, ...
Each Solider will have different id and level. Time to create a type of Solider is 3 seconds.
- The program we installed with the Flyweigth Pattern is as follows:
• ISoldier: acts as a Flyweight. Promote method is defined with context parameter, this parameter
value is decided by the Client.
• Context: acts as Extrinsic State. Different contexts will have different values.
• Soldier: acts as ConcreteFlyweight. Implement the methods defined in Flyweight. It has a value
(corresponding to soldier type - Intrinsic State) that is immutable, shareable.
• SoldierFactory: acts as FlyweightFactory. It holds a private Map to store the types of soldiers that
have been created. A createSoldier () method to create a soldier with the type name is passed. A
method getTotalOfSoldiers () to check the number of soldier types created.
• GameApp: acts as a Client. Use SoldierFactory to create Soldiers.

- Class diagram:

Figure 19: Flywiegh class diagram.


- Source code:
public interface ISoldier
{

void promote(Context context);

}
public class Context
{

private String id;


private int star;

public Context(String id, int star)


{
this.id = id;
this.star = star;
}

public String getId()


{
return this.id;
}

public int getStar()


{
return this.star;
}
}
public class Soldier : ISoldier
{

private string name;

public Soldier(string name)


{
this.name = name;
Console.WriteLine("Soldier is created! - " + name);
}

public void promote(Context context)


{
Console.WriteLine(name + " " + context.getId() + " promoted " + context.getStar());
}
}
public class SoldierFactory
{

private static Dictionary<string, ISoldier> soldiers = new Dictionary<string, ISoldier>();

private SoldierFactory()
{
throw new ArgumentException ;
}

public static ISoldier createSoldier(string name)


{
ISoldier soldier = soldiers.GetType();
if (soldier == null)
{
waitingForCreateASoldier();
soldier = new Soldier(name);
soldiers.Add(name, soldier);
}
return soldier;
}

public static int getTotalOfSoldiers()


{
return soldiers.size();
}

private static void waitingForCreateASoldier()


{
try
{
Thread.sleep(3000);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.StackTrace) ;
}
}
}
class Program
{
static void Main(string[] args)
{
private static List<ISoldier> soldiers = new List<ISoldier>();

public static void main(String[] args)


{
long startTime = System.currentTimeMillis();
createSoldier(5, "Yuri", 1);
createSoldier(5, "Spy", 1);
createSoldier(3, "Spy", 3);
createSoldier(2, "Yuri", 2);
long endTime = System.currentTimeMillis();
Console.WriteLine("---");
Console.WriteLine("Total soldiers made : " + soldiers.size());
Console.WriteLine("Total time worked : " + Duration.ofMillis(endTime -
startTime).getSeconds() + " seconds");
Console.WriteLine("Total type of soldiers made : " +
SoldierFactory.getTotalOfSoldiers());
}

private static void createSoldier(int numberOfSoldier, String soldierName, int


numberOfStar)
{
for (int i = 1; i <= numberOfSoldier; i++)
{
Context star = new Context("Soldier" + (soldiers.size() + 1), numberOfStar);
ISoldier soldier = SoldierFactory.createSoldier(soldierName);
soldier.promote(star);
soldiers.add(soldier);
}
}
}

After executing with the c # code is complete. We run the program and the results are printed as the image
below

Figure 20: Result.


3.3 Behavioral Pattern :
a) Definition :
- In software engineering, behavioral design is a design pattern that defines and defines common
communication patterns between objects. By doing so, these models increase the flexibility in making
communication of objects.

- Behavioral pattern include both of the following:

• Chain of responsibility: is a way to transfer requests between a chain of objects.


• Iterator: continuous access to the components of the selector.
• Mediator: Defines simplified communication between classes
• Memento: Capture and restore an object's internal state
• Observer: A way of notifying change to a number of classes
• Null Object: designed to act as the default value of the object.
• State: changes the behavior of an object when its state changes.
• Strategy: Pack an algorithm inside a layer.
• Interpreter: A way to include language elements in a program
• Visitor: Defines a new operation to a class without change
• Template method: Defines the skeleton of the exact steps of an algorithm for each class.

-There are many design patterns in the Behavioral pattern, but we have chosen one to explain and draw
diagrams to illustrate them and explain why they are used.

-The sample we chose to draw and illustrate is a Stragery.

• Definition: Define a set of algorithms, package them one by one and make it interchangeable.
Strategy makes the algorithm independent of its use in client computers. Enables abstraction in an
interface, detailed implementation in the root class. (NONE, 2019)
Figure 21: Stragery class diagram.

-The classes and objects participating in this pattern are:

+ Strategy : declares an interface common to all supported algorithms. Context uses this interface to call
the algorithm defined by a ConcreteStrategy

+ ConcreteStrategy : implements the algorithm using the Strategy interface

+ Context :

• Is configured with a ConcreteStrategy object


• Maintains a reference to a Strategy object
• May define an interface that lets Strategy access its data.

b) Why use it?


- The reason we use stragery pattern is for the following purposes:

- Strategy Pattern is to help separate the handling of a specific function from the object. Then create a set of
algorithms to handle that function and choose which algorithm we find the best fit when executing the
program. This design pattern is often used as a replacement for inheritance, when it wants to end tracking
and editing a function across multiple subclasses.

- When desired, the algorithms used within an object can be changed at run-time.

- When there is a piece of code that is easy to change, and wants to separate it from the main program for
easy maintenance.
- Avoid the hassle of having to implement a certain function through so many subclasses.

- Need to hide the complexity, the internal structure of the algorithm.

c) How to use it with source code demonstration:


We will build a given string encryption application as an example for this Dessign Patten. There are three
encryption algorithms (RAS algorithm, DES algorithm and blowfish algorithm) available to encrypt the
given value and the end user can use any one of them. The encryption algorithm will be selected at run time.
Here, we will use Strategy Patten as the representative for this Design Patten.

Class Diagram

Figure 22: Stragery class diagram.

Participants in above UML diagram are:

• IEncodingStrategy: IStrategy interface


• RASEncodingStrategy: ConcreteStrategyA class
• DESEncodingStrategy: ConcreteStrategyB class
• BlowFishEncodingStrategy: ConcreteStrategyC class
• Encoding: Context class

Source Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StrategyPatternDemo
{
//'IStrategy' interface
public interface IEncodingStrategy
{
void EncodeValue(string value);
}
//'ConcreteStrategyA' class
public class RSAEncodingStrategy : IEncodingStrategy
{
public void EncodeValue(string value)
{
// Implement Encoding strategy
Console.WriteLine("Value {0} is Encoded using RSA Algorithm", value);
}
}
//'ConcreteStrategyB' class
public class DESncodingStrategy : IEncodingStrategy
{
public void EncodeValue(string value)
{
// Implement Encoding strategy
Console.WriteLine("Value {0} is Encoded using DES Algorithm", value);
}
}

//'ConcreteStrategyC' class
public class BlowFishEncodingStrategy : IEncodingStrategy
{
public void EncodeValue(string value)
{
// Implement Encoding strategy
Console.WriteLine("Value {0} is Encoded using BlowFish Algorithm", value);
}
}

//'Context' class
public class Encoding
{
private IEncodingStrategy _encodeStrategy;

public Encoding(IEncodingStrategy encodeStrategy)


{
_encodeStrategy = encodeStrategy;
}

public void Encode(string value)


{
_encodeStrategy.EncodeValue(value);
}
}

class Program
{
static void Main(string[] args)
{
IEncodingStrategy encodingStrategy = new RSAEncodingStrategy();
Encoding encoding = new Encoding(encodingStrategy);
encoding.Encode("10000011110");

encodingStrategy = new DESncodingStrategy();


encoding = new Encoding(encodingStrategy);
encoding.Encode("10000011110");

encodingStrategy = new BlowFishEncodingStrategy();


encoding = new Encoding(encodingStrategy);
encoding.Encode("10000011110");

Console.ReadLine();
}
}
}

After executing with the c # code is complete. We run the program and the results are printed as the image
below

Figure 23: Stragery result.


Bibliography
Giang, 2019. VIBLO. [Online]
Available at: https://viblo.asia/p/tong-hop-cac-bai-huong-dan-ve-design-pattern-23-mau-co-ban-cua-gof-
3P0lPQPG5ox

Hieu, 2017. TechTalk. [Online]


Available at: https://techtalk.vn/tong-quan-cac-mau-design-pattern.html

Khanh, 2019. VIBLO. [Online]


Available at: https://gpcoder.com/4434-huong-dan-java-design-pattern-builder/

NONE, 2019. VIBLO. [Online]


Available at: https://gpcoder.com/4796-huong-dan-java-design-pattern-strategy/

NONE, n.d. VIBLO. [Online]


Available at: https://gpcoder.com/4626-huong-dan-java-design-pattern-flyweight/

Das könnte Ihnen auch gefallen