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');
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.
Please give an explanation or what the rational of the code is about, I am trying...
Please give an explanation or what the rational of the code is about, I am trying to figure it out what it means so to better understand it. Discuss the Code Provision on Square and Rectangular HSS and Box- Shaped Members, Rounds HSS, Tees and Double Angles Loaded in the Plane of Symmetry, and Single Angles.
I am trying to write the code for an 8 bit adder in VHDL so that...
I am trying to write the code for an 8 bit adder in VHDL so that I can program it onto my Elbert V2 Spartan 3A FPGA Development Board, but I keep getting errors. Any ideas what I am doing wrong? library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity adder8bit is Port ( a : in STD_LOGIC_VECTOR(7 downto 0); b : in STD_LOGIC_VECTOR(7 downto 0); cin : in STD_LOGIC; o : out STD_LOGIC_VECTOR(7 downto 0); cout : out STD_LOGIC); end adder8bit; architecture Behavioral...
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...
I am trying to implement a search function for a binary search tree. I am trying...
I am trying to implement a search function for a binary search tree. I am trying to get the output to print each element preceding the the target of the search. For example, in the code when I search for 19, the output should be "5-8-9-18-20-19" Please only modify the search function and also please walk me through what I did wrong. I am trying to figure this out. Here is my code: #include<iostream> using namespace std; class node {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT