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

Prototype Pattern

prototype
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Prototype Pattern

prototype
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

Prototype

& Singleton
Design Pattern
`
Prototype Pattern

• A creational pattern
• Specify the kinds of objects to create using a prototypical
instance, and create new objects by copying this prototype
Problem
Prototype solution
Prototype Pattern UML

Participants:
• Prototype
o declares an
interface for cloning
itself.

ConcretePrototyp
e o implements an
operation for cloning
itself.
• Client
o creates a new
object by asking a
prototype to clone
itself.
Exampl
e
Animal farm
Prototype Pattern Example code
Prototype Pattern Example code
Prototype Pattern Example code
Prototype Pattern

When to Use
• When product creation should be decoupled from system behavior
• When to avoid subclasses of an object creator in the client
application
• When creating an instance of a class is time-consuming or complex in
some way.
Consequences of Prototype
Pattern
• Hides the concrete product classes from the client
• Adding/removing of prototypes at run-time
• Allows specifying new objects by varying values or structure
• Reducing the need for sub-classing
Drawbacks of Prototype Pattern

• It is built on the method .clone(), which could be complicated


sometimes in terms of shallow copy and deep copy. Moreover,
classes that have circular references to other classes cannot really be
cloned.
What is the Prototype Design Pattern?

• As per the GoF Definition, “Prototype Design Pattern


specifies the kind of objects to create using a prototypical
instance, and create new objects by copying this prototype”.

• To simplify the above definition, we can say that,


the Prototype Design Pattern gives us a way to create new
objects from the existing instance of the object. That means
it clone the existing object with its data into a new object. If
we do any changes to the cloned object (i.e. new object)
then it does not affect the original object.
Understanding the Prototype Design Pattern

• Let us understand the Prototype Design Pattern with an


example. In C#, when we try to copy one object to
another object using the assignment (=) operator, then
both the objects will share the same memory address.
And the reason is the assignment operator (=) copies
the reference, not the object except when there is a
value type field. This operator will always copy the
reference, not the actual object.
Please have a look at the following image.
• As you can see in the above image, we have one
Employee class. Then we create an instance of
Employee class (i.e. emp1) and set its Name and
Department properties. Then we create another
employee instance (i.e. emp2) by assigning the existing
employee object (i.e. emp1). When we change the
Name of emp2 then it also changes the name of the
emp1.
• class Program
• {
• static void Main(string[] args)
• {
• Employee emp1 = new Employee();
• emp1.Name = "Anurag";
• emp1.Department = "IT";
• Employee emp2 = emp1;
• emp2.Name = "Pranaya";
• Console.WriteLine("Emplpyee 1: ");
• Console.WriteLine("Name: " + emp1.Name + ", Department: " +
emp1.Department);
• Console.WriteLine("Emplpyee 2: ");
• Console.WriteLine("Name: " + emp2.Name + ", Department: " +
emp2.Department);
• Console.Read();
• }
• }
• public class Employee
• {
• public string Name { get; set; }
• public string Department { get; set; }
• }
Output
Understanding Object Cloning:

• When we talk about object cloning it means it is all


about the call by value. So, if we do any changes to
one object then it will not affect the other object. Let us
see how to clone the object to another object. To do so,
C# provides one method i.e. MemberwiseClone which
will create a new complete copy of the object.
• As shown in the above image, within the Employee class, we
created one method i.e. GetClone and as part of that method, we
are returning a clone object using the MemberwiseClone method.
Then from the client code, first we are creating a new instance of
the Employee class and assigning the properties with some
values. Next, we are creating the second object by calling the
GetClone method which in turn returns a new complete copy of the
emp1 object. Now, both the objects (i.e. emp1 and emp2) are
independent and if we do any changes to any object, then it will
not affect other objects.
Prototype Design Pattern in C# with Example: Object Cloning

• class Program
• {
• static void Main(string[] args)
• {
• Employee emp1 = new Employee();
• emp1.Name = "Anurag";
• emp1.Department = "IT";
• Employee emp2 = emp1.GetClone();
• emp2.Name = "Pranaya";
• Console.WriteLine("Emplpyee 1: ");
• Console.WriteLine("Name: " + emp1.Name + ", Department: " +
emp1.Department);
• Console.WriteLine("Emplpyee 2: ");
• Console.WriteLine("Name: " + emp2.Name + ", Department: " +
emp2.Department);
• Console.Read();
• }
• }
• public class Employee
•{
• public string Name { get; set; }
• public string Department { get; set; }
• public Employee GetClone()
•{
• return (Employee)this.MemberwiseClone();
•}
Output
• Singleton
.• Intent
• Singleton is a creational design pattern that lets you
ensure that a class has only one instance, while providing
a global access point to this instance.
Problem
The Singleton pattern solves two problems at the
same time, violating the Single Responsibility
Principle:
1.Ensure that a class has just a single
instance. Why would anyone want to control how
many instances a class has? The most common
reason for this is to control access to some shared
resource—for example, a database or a file.
2.Here’s how it works: imagine that you created
an object, but after a while decided to create a
new one. Instead of receiving a fresh object, you’ll
get the one you already created.
3.Note that this behavior is impossible to
implement with a regular constructor since a
constructor call must always return a new object
by design.
2.Provide a global access point to that
instance. Remember those global variables that
you (all right, me) used to store some essential
objects? While they’re very handy, they’re also
very unsafe since any code can potentially
overwrite the contents of those variables and
crash the app.
3.Just like a global variable, the Singleton pattern
lets you access some object from anywhere in
the program. However, it also protects that
instance from being overwritten by other code.
4.There’s another side to this problem: you don’t
want the code that solves problem #1 to be
scattered all over your program. It’s much
better to have it within one class, especially if the
rest of your code already depends on it.
Nowadays, the Singleton pattern has become so
Solution
All implementations of the Singleton have these
two steps in common:

1.Make the default constructor private, to


prevent other objects from using the new
operator with the Singleton class.
2.Create a static creation method that acts as a
constructor.
3.Under the hood, this method calls the private
constructor to create an object and saves it in a
static field.
4.All following calls to this method return the
Real-World Analogy
The government is an excellent example of the
Singleton pattern. A country can have only one
official government. Regardless of the personal
identities of the individuals who form governments,
the title, “The Government of X”, is a global point of
access that identifies the group of people in charge.

Structure
The Singleton class declares the static method
getInstance that returns the same instance of its own
class.

The Singleton’s constructor should be hidden from the


client code.
Calling the getInstance method should be the only
way of getting the Singleton object.
• As you can see in the above diagram, different clients (NewObject a,
NewObject b and NewObject n) trying to get the singleton instance. Once
the client gets the singleton instance then they can invoke the methods
(Method 1, Method 2, and Method n) using the same instance. If this is
confused at the moment then don’t worry we will discuss it with practice.
What are the Advantages of using the
Singleton Pattern
• The Advantages of using the Singleton Design Pattern are as follows.

1.The first and most important advantage of using the singleton design pattern in C# is
that it takes care of concurrent access to the shared resource. That means if we are
sharing a resource with multiple clients simultaneously, then concurrent access to that
resource is well managed by the singleton design pattern.

2.It can be lazy-loaded and also has Static Initialization.

3.To share common data i.e. master data and configuration data which is not changed that
frequently in an application. In that case, we need to cache the objects in memory.

4.As it provides a single global point of access to a particular instance, so it is easy to


maintain.

5.To reduce the overhead of instantiating a heavy object again and again.
SINGLETON IMPLEMENTATION
METHODS
1. EAGER
2. LAZY
3. SYNCHRONIZED METHOD
4. DOUBLE LOCKING
1. EAGER
2.LAZY INITIALIZATION
3.SYNCHRONIZED METHOD
4.DOUBLE LOCKING

You might also like