In: Computer Science
I am trying to integrate a Singleton Pattern into this code I had previously made.
Here is my code to a previous project:
radius = float(input("Please enter the radius: ")) area = 3.14 * radius**2; print("The area is ", area, "square units.")
For this project it must be coded in python.
Here are the instructions for the project for reference.
Implementing Design Patterns with Python
Software Design Patterns may be thought of as blue prints or recipes for implementing common models in software. Much like re-using proven classes in Object Oriented design, re-using proven patterns tends to produce more secure and reliable results often in reduced time compared to re-inventing the wheel. In fact, some high-level languages have integrated facilities to support many common patterns with only minimal, if any, user written software. That said, in software design and construction, often the challenge is to know that a pattern exists and be able to recognize when it is a good fit for a project. To give you a familiar frame of reference, below is a Singleton Pattern implemented in Java:
public class MySingleton {
// reference to class instance
private static MySingleton instance = null;
// Private Constructor
private MySingleton() {
instance = this;
}
// Returns single instance to class
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
public static void main(String[] args)
{
MySingleton s1 = MySingleton.getInstance();
MySingleton s2 = MySingleton.getInstance();
System.out.println("s1: " + s1 + " s2: " + s2);
}
}
If you run this example, you will see that the address for s1 and s2 are exactly the same. That is because the pattern restricts the existence of more than one instance in a process. Of course this example only implements the pattern but other functionality can be added to this class just as any other class. The primary features of a singleton are:
The primary goal of this assignment is not to teach you how to write singleton patterns in Python, (though that’s part of it), but to familiarize you with the concept of design patterns as well as give you experience in adapting one into one of your own designs.
Description
Hi. I have answered similar questions before. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#code
class AreaCalculator:
__instance = None # single
instance
# Initialize the constant
PI = 3.14
# variable for storing radius
__radius = 0
# method to create the instance of
AreaCalculator, constructor should not be used
@staticmethod
def getInstance():
# if __instance is
None, initializing it
if
AreaCalculator.__instance == None:
AreaCalculator.__instance = AreaCalculator()
# returning
__instance
return AreaCalculator.__instance
# constructor
def __init__(self):
# if __instance is
not None, throwing exception, because all objects (copies)
should
# be created using
getInstance method only
if
AreaCalculator.__instance != None:
raise Exception('AreaCalculator should be
initialized using getInstance() method only')
# method to set radius of the circle
@staticmethod
def setRadius(radius):
AreaCalculator.__radius=radius
# method to compute area and return it
@staticmethod
def calculateArea():
area=AreaCalculator.PI*
AreaCalculator.__radius**2
return
area
# main method for testing
def main():
# creating two instances (will only be a
single instance internally)
a1 = AreaCalculator.getInstance()
a2 = AreaCalculator.getInstance()
# printing both instances to let the user
know that they are same
print('First object:',
a1)
print('Second object:',
a2)
# Request the inputs
radius = float(input("Please enter
the radius: "))
# setting inputs using setRadius method,
only using one object
a1.setRadius(radius)
# Display the area using both objects
print("(Using First object) The
area is", a1.calculateArea(),"square
units.")
print("(Using Second object) The area
is", a2.calculateArea(), "square
units.")
main()
#output
First object: <__main__.AreaCalculator object at 0x03A66070> Second object: <__main__.AreaCalculator object at 0x03A66070> Please enter the radius: 52 (Using First object) The area is 8490.56 square units. (Using Second object) The area is 8490.56 square units.