Question: ## Observer Pattern ### Ex: Create a program that simulates a stock market. The program should consist of two classes: * * ` Stock `

## Observer Pattern
### Ex:
Create a program that simulates a stock market. The program should consist of two classes: **`Stock`** and **`Investor`**.
The **`Stock`** class should have the following properties:
-**`symbol`**(string): The stock symbol (e.g., "AAPL").
-**`price`**(float): The current price of the stock.
-**`investors`**(list): A list of **`Investor`** objects that have invested in the stock.
-**`register_investor(self, investor)`**: A method that adds an **`Investor`** object to the list of investors.
-**`unregister_investor(self, investor)`**: A method that removes an **`Investor`** object from the list of investors.
-**`update_price(self, price)`**: A method that updates the price of the stock and notifies all investors that have invested in the stock.
The **`Investor`** class should have the following properties:
-**`name`**(string): The name of the investor.
-**`stocks`**(list): A list of **`Stock`** objects that the investor has invested in.
-**`update(self, stock, price)`**: A method that is called by a **`Stock`** object to notify the investor of a change in price.
Here are some additional requirements for the program:
- The program should allow the user to create multiple **`Stock`** objects and multiple **`Investor`** objects.
- The user should be able to register an **`Investor`** object with a **`Stock`** object and unregister an **`Investor`** object from a **`Stock`** object.
- The user should be able to update the price of a **`Stock`** object and see the changes reflected in all the **`Investor`** objects that have invested in that stock.
To complete the exercise, you will need to implement the observer pattern in your program. The **`Stock`** class should be the subject, and the **`Investor`** class should be the observer. When the price of a **`Stock`** object is updated, the **`Stock`** object should notify all the **`Investor`** objects that have invested in that stock.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!