1. Definition
The Prototype Design Pattern involves creating objects based on a template of an existing object through cloning. Instead of creating a new instance of an object from scratch, a copy of an existing instance is made.
2. Problem Statement
Consider scenarios where object creation is a costly affair in terms of resources, time, or both. In such situations, creating multiple instances from scratch is inefficient. Yet, you may need multiple objects that are similar but not identical.
3. Solution
The Prototype pattern helps by allowing objects to be cloned, giving a faster alternative to new object instantiation. A prototype object is created, and new objects are cloned from this prototype when needed, possibly with some modifications.
4. Real-World Use Cases
1. In video games, to clone characters, weapons, or items.
2. In document editors, clone shapes or styles for consistency.
3. Creating unique instances of data from a default configuration.
5. Implementation Steps
1. Create a prototype interface with a 'clone' method.
2. Concrete classes will implement this interface to offer a cloning capability.
3. Use the 'clone' method to produce new objects rather than using the 'new' keyword.
6. Implementation in Ruby
# Step 1: Prototype Interface
module Prototype
def clone
raise NotImplementedError
end
end
# Step 2: Concrete class implementing the Prototype interface
class ConcretePrototype
include Prototype
attr_accessor :data
def initialize(data)
@data = data
end
# Implementing the clone method
def clone
# In Ruby, dup creates a shallow copy of an object.
copy = self.dup
# Perform any other deep copy or modifications if needed
copy
end
def show_data
@data
end
end
# Client Code
prototype = ConcretePrototype.new("Original Data")
copy = prototype.clone
copy.data = "Cloned Data"
prototype.show_data
copy.show_data
Output:
Original Data Cloned Data
Explanation:
1. The Prototype module provides an interface with a 'clone' method which every concrete prototype should implement.
2. The ConcretePrototype class includes this module and implements the 'clone' method. Here, we used Ruby's dup method which provides a shallow copy of an object.
3. In the client code, an object is cloned from the prototype, and its data is modified to show that the cloned object is a different instance.
7. When to use?
Use the Prototype Pattern when:
1. Classes to instantiate are specified at runtime.
2. Objects can be cloned into different configurations without involving subclassing.
3. Instantiation of a class is more costly than cloning an existing instance.
Comments
Post a Comment