Question

In: Computer Science

I am trying to integrate a Singleton Pattern into this code I had previously made. Here...

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:

  1. Private or restricted constructor
  2. Internal variable for holding reference to single instance
  3. Static method for retrieving the instance

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

  1. Using an Internet Search Engine, search for common software design patterns. Describe, in your own words, how one of these patterns could be used in an application or software task. You are expected to write professionally, with proper grammar and spelling, but you are not required to adhere to a specific format or cite any sources.
  2. Pick one of your previous assignments, either from MindTap or one of your Distributed Systems assignments and integrate a Singleton Pattern into it. Hint: Any class can be made into a Singleton.

Solutions

Expert Solution

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.

Related Solutions

Using Python, I am trying to integrate 'iloc' into the line of code below? This line...
Using Python, I am trying to integrate 'iloc' into the line of code below? This line is replacing all the '1' values across my .csv file and is throwing off my data aggregation. How would I implement 'iloc' so that this line of code only changes the '1's integers in my 'RIC' column? patient_data_df= patient_data_df.replace(to_replace=[1], value ="Stroke") Thank you:)
I am trying to do edge detection using matlab. I have posted code here. It does...
I am trying to do edge detection using matlab. I have posted code here. It does not give any error but it's not running it at all. So please help me to fix it and also exaplin each line of this code pls. Thanks! i = imread('C:\Users\Amanda\Desktop"); I = rgb2gray(1i); BW1 = edge(I,'prewitt'); BW2= edge(I,'sobel'); BW3= edge(I,'roberts'); subplot (2,2,1); imshow(I); title('original'); subplot(2,2,2); imshow(BW1); title('Prewitt'); subplot(2,2,3); imshow(BW2); title('Sobel'); subplot(2,2,4); imshow(BW3); title('Roberts');
I am trying to get this code to work but I am having difficulties, would like...
I am trying to get this code to work but I am having difficulties, would like to see if some one can solve it. I tried to start it but im not sure what im doing wrong. please explain if possible package edu.hfcc; /* * Create Java application that will create Fruit class and Bread class * * Fruit class will have 3 data fields name and quantity which you can change. * The third data field price should always...
Assembly Question: I am trying to annotate this code and am struggling to understand what it...
Assembly Question: I am trying to annotate this code and am struggling to understand what it is doing. Can someone please add comments? .data .star: .string "*" .line: .string "\n" .input: .string "%d" .count: .space 8 .text .global main printstars: push %rsi push %rdi _printstars: push %rdi mov $.star, %rdi xor %rax, %rax call printf pop %rdi dec %rdi cmp $0, %rdi jg _printstars mov $.line, %rdi xor %rax, %rax call printf pop %rdi pop %rsi ret printstarpyramid: mov %rdi,...
Here is my fibonacci code using pthreads. When I run the code, I am asked for...
Here is my fibonacci code using pthreads. When I run the code, I am asked for a number; however, when I enter in a number, I get my error message of "invalid character." ALSO, if I enter "55" as a number, my code automatically terminates to 0. I copied my code below. PLEASE HELP WITH THE ERROR!!! #include #include #include #include #include int shared_data[10000]; void *fibonacci_thread(void* params); void parent(int* numbers); int main() {    int numbers = 0; //user input....
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
I am trying to write a code in C for a circuit board reads in a...
I am trying to write a code in C for a circuit board reads in a temperature from a sensor on the circuit board and reads it onto a 7-segment LED display. How exactly would you code a floating 2 or 3 digit reading onto the LED display? I am stuck on this part.
this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
Not sure how to prompt these functions here. I am trying tocreate a holiday shopping...
Not sure how to prompt these functions here. I am trying to create a holiday shopping list. Here are my three requirements'''This function should prompt the user for the names of all the family members that they will be purchasing gifts for this holiday and return those names in a list'''def family_names():names = []return names'''This function takes the names of all family members as a list and asks the user how much money they will spend on each person. These...
Here is the following information on the Cheesecake Factory, I am trying to answer question 1...
Here is the following information on the Cheesecake Factory, I am trying to answer question 1 below. Can you please help me out? Excel assignment. Current Dividend (Source – Yahoo!Finance) $1.28 Required Return (Estimated) 8.9% Current EPS (Source – Yahoo!Finance) $2.14 Current Book Value Per Share (Source – Yahoo!Finance) $13.24 Current EBITDA per share (Source – Yahoo!Finance) $5.25 Current Debt per share è $2.80 Current Cash and Equivalents per share $0.61 Initial Growth Rate for H-Model (Estimated) 9% Terminal Growth...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT