Skip to content

Commit cad27a0

Browse files
committed
Update: Added design patterns
1 parent 5445497 commit cad27a0

File tree

2 files changed

+171
-0
lines changed

2 files changed

+171
-0
lines changed

Model-View-Controllers/README.md

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Model-View-Controller (MVC) - A 2048 Game in JavaFX
2+
3+
The **Model-View-Controller (MVC)** directory demonstrates the implementation of the **MVC design pattern** in a **2048 puzzle game** using **JavaFX**. The MVC pattern is a widely used software design principle that divides an application into three interconnected components, enhancing modularity and enabling efficient management of user interfaces, logic, and data.
4+
5+
In this directory, the MVC pattern is used to clearly separate the game's core logic (Model), user interface (View), and user input handling (Controller). This separation of concerns allows for better code organization, easier maintenance, and scalability.
6+
7+
## Overview of MVC Pattern in the 2048 Game
8+
9+
In this project, the **MVC pattern** is implemented to manage the game's functionality in three distinct layers:
10+
11+
- **Model**: Handles the game state and logic (e.g., board, score, tile movements, and merging).
12+
- **View**: Displays the game’s interface, including the grid, tiles, and scores.
13+
- **Controller**: Manages user input (e.g., arrow keys for tile movement) and updates both the Model and View accordingly.
14+
15+
Each of these components is designed to interact with one another but remain independent, which helps in isolating logic, simplifying testing, and allowing each component to evolve independently.
16+
17+
## Key Components of the MVC Architecture
18+
19+
### 1. **Model (Game2048)**
20+
21+
The **Model** is the core of the game, responsible for managing the game state and implementing game rules. In the case of this 2048 game, the model handles the board state, tile movements, merging of tiles, adding new tiles, and detecting game over conditions.
22+
23+
#### Key Features:
24+
- **Game State**: The grid (represented as a 2D array) and the score are stored in the `board` and `score` properties.
25+
- **Tile Logic**: It includes methods for merging tiles when two tiles with the same value collide and adding new tiles (either a 2 or 4) after every move.
26+
- **Game Over Check**: The Model checks if the game is over when there are no available moves left.
27+
28+
The Model is completely independent of the user interface, making it easily testable and reusable. It’s updated by the Controller, and the View simply reflects the current state of the Model.
29+
30+
### 2. **View (Main)**
31+
32+
The **View** represents the graphical user interface (GUI). In this game, the View is implemented using **JavaFX**, which provides various components like labels, buttons, and panes to display the game.
33+
34+
#### Key Features:
35+
- **Grid Rendering**: The View displays a 4x4 grid, where each tile has a value. It dynamically updates the UI whenever the game state changes.
36+
- **Score Display**: The View updates the current score and the best score.
37+
- **Animations**: The View includes smooth animations for tile movement and merging, which make the gameplay visually appealing.
38+
- **User Interface**: Includes buttons for starting a new game or exiting the game.
39+
40+
The View is responsible for presenting the Model's data to the user and does not contain any game logic. It listens for updates from the Controller and reflects those changes on the screen.
41+
42+
### 3. **Controller (GameController)**
43+
44+
The **Controller** acts as an intermediary between the Model and the View. It listens for user input (such as key presses for moving the tiles) and then updates the Model accordingly. It also notifies the View to update the display after each action.
45+
46+
#### Key Features:
47+
- **Input Handling**: The Controller listens for arrow key presses (Up, Down, Left, Right) and passes this input to the Model to perform the corresponding action (e.g., moving tiles).
48+
- **Game Updates**: After each valid move, the Controller calls methods on the Model to update the board and score. It then notifies the View to render the new state.
49+
- **Game Reset**: The Controller handles the logic for starting a new game or exiting the game.
50+
51+
The Controller does not directly manipulate the game’s data but orchestrates the interactions between the Model and View. It decouples the user interface from the game logic, making the system more flexible and maintainable.
52+
53+
## Key Design Patterns Used
54+
55+
### **Model-View-Controller (MVC) Pattern**
56+
57+
The **MVC pattern** is at the heart of this implementation. It divides the game into three distinct parts:
58+
- **Model**: Manages the game’s state and logic.
59+
- **View**: Handles rendering and updating the user interface.
60+
- **Controller**: Processes user inputs and updates both the Model and View.
61+
62+
This separation allows for a clear organization of code, makes each component easier to manage, and allows for easier updates and testing.
63+
64+
## Advantages of Using MVC in the 2048 Game
65+
66+
- **Separation of Concerns**: The logic is separate from the user interface. The game mechanics (Model) and rendering (View) can be developed and modified independently.
67+
- **Maintainability**: Each part of the game is isolated, making it easier to test, debug, and extend.
68+
- **Reusability**: The Model can be reused with a different View (e.g., console-based) if desired.
69+
- **Flexibility**: It’s easy to add new features like additional animations or game modes without disturbing the core logic or interface.
70+
71+
## Conclusion
72+
73+
This directory demonstrates the use of the **Model-View-Controller (MVC) design pattern** to implement a **2048 game in JavaFX**. By separating the game logic, user interface, and user input handling, the code is made more modular, maintainable, and flexible. The MVC pattern also enhances the game’s scalability, making it easy to add new features or even change the game’s presentation style without altering the underlying game mechanics.

Observers/README.md

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# `Observers` Directory - A Price Watching Application Using the Observer Design Pattern
2+
3+
The **Observers** directory demonstrates the application of the **Observer Design Pattern** within the context of a **price-watching application** for a mall shopping scenario. This application simulates a customer trying to monitor sales events at multiple stores in order to buy products at the best prices. The Observer pattern allows customers (observers) to receive updates from stores (subjects) whenever a relevant sale event occurs, such as a product going on sale or coming back in stock.
4+
5+
In this directory, the Observer pattern is used to notify customers of various sales events, and customers can react to these notifications by purchasing products or waiting for better deals. This setup not only demonstrates how the Observer pattern works but also provides a real-world example of how this design pattern can be applied in interactive applications.
6+
7+
## Overview of the Observer Pattern
8+
9+
The **Observer Design Pattern** is a behavioral pattern where an object (the **subject**) maintains a list of its dependents (the **observers**) and notifies them of any state changes, usually by calling one of their methods. This pattern is commonly used for implementing distributed event handling systems.
10+
11+
In this project, **stores** are the subjects, and **customers** are the observers. When an event like a sale starts, a product restocking, or an out-of-stock situation occurs, the store notifies all of its registered customers about the event.
12+
13+
### Key Concepts:
14+
1. **Subject**: The object that holds a list of observers and notifies them about changes.
15+
2. **Observer**: The object that receives updates from the subject when an event occurs.
16+
3. **Event**: Represents a specific occurrence that the observers are interested in (e.g., a sale starting or an item going out of stock).
17+
18+
## Key Components of the Observer Pattern in the Application
19+
20+
### 1. **Event Classes (`StoreEvent`)**
21+
22+
In this application, there are different types of sale events that customers may want to observe. These events are encapsulated as concrete classes implementing the `StoreEvent` interface.
23+
24+
#### Types of Events:
25+
- **`BackInStockEvent`**: This event occurs when a product that was previously out of stock is now available for purchase.
26+
- **`OutOfStockEvent`**: This event occurs when a product is sold out (i.e., no stock left).
27+
- **`PurchaseEvent`**: This event occurs when a product is purchased from a store.
28+
- **`SaleEndEvent`**: This event signals that a sale on a particular product has ended.
29+
- **`SaleStartEvent`**: This event signals the start of a sale on a product.
30+
31+
Each event class encapsulates a **`Product`** and a **`Store`**, and implements the `StoreEvent` interface. These events are immutable and notify observers (customers) about the changes.
32+
33+
### 2. **Product (`ProductImpl`)**
34+
35+
The `ProductImpl` class represents a product in the store. Each product has a name and a base price. Products may also have additional properties, such as sale prices or availability (whether they're in stock or not).
36+
37+
#### Key Features:
38+
- **Product Name**: The name of the product.
39+
- **Base Price**: The product's original price before any discounts.
40+
- **Sale Price** (optional): The price of the product if it's on sale.
41+
42+
### 3. **Store (`StoreImpl`)**
43+
44+
The `StoreImpl` class represents a store in the mall. It maintains a list of products and also tracks the customers who are observing the store for sale events. The store is the **subject** in the observer pattern and notifies its observers whenever a relevant event occurs.
45+
46+
#### Key Features:
47+
- **Products**: The list of products that the store sells.
48+
- **Observers**: A list of customers (observers) who are registered to receive notifications from the store.
49+
- **Inventory and Sale Information**: The store tracks how many units of each product are in stock and whether any sales are active.
50+
- **Methods**:
51+
- `startSale()`: Starts a sale for a product and notifies customers.
52+
- `endSale()`: Ends a sale for a product and notifies customers.
53+
- `restockProduct()`: Restocks a product and notifies customers if it is back in stock.
54+
- `purchaseProduct()`: Processes a purchase, deducts stock, and notifies customers of the purchase event.
55+
56+
### 4. **Customer (`CustomerImpl`)**
57+
58+
The `CustomerImpl` class represents a customer who is observing stores for sales events. Customers are **observers** in the observer pattern and respond to events by purchasing products or simply observing sales announcements.
59+
60+
#### Key Features:
61+
- **Customer Information**: The customer's name and budget.
62+
- **Purchasing**: Customers can purchase products if they have enough money in their budget. A `ReceiptItem` object is created to record each purchase.
63+
- **Event Handling**: The `update()` method handles incoming sale events, such as when a product goes on sale or comes back in stock. It prints messages to the console to inform the customer about the event.
64+
65+
### 5. **Main Class (`Main`)**
66+
67+
The `Main` class is responsible for simulating the shopping experience in the mall. It initializes stores, products, and customers. It also registers customers as observers of the stores, so they can be notified of events.
68+
69+
#### Key Features:
70+
- **Game Loop**: Simulates a mall shopping trip, where customers monitor stores for deals.
71+
- **Customer and Store Registration**: Customers can register or deregister as observers of stores.
72+
- **Console Interaction**: Provides a simple command-line interface where customers can view events and make purchases.
73+
74+
## How the Observer Pattern Works
75+
76+
1. **Store (Subject)**: A store contains a list of observers (customers) and notifies them whenever a relevant event occurs (e.g., a product going on sale, restocking, or being sold out).
77+
2. **Customer (Observer)**: A customer listens for store events. When a store announces a sale, the customer receives the notification through the `update()` method, which then processes the event (e.g., prints a message to the console and possibly makes a purchase).
78+
3. **Event**: Each type of event (`BackInStockEvent`, `SaleStartEvent`, etc.) encapsulates the product and the store where the event occurred. When an event happens, it is passed to all observers who are interested in that store.
79+
80+
### Example Event Flow:
81+
- A store starts a sale on a product.
82+
- The store notifies all registered customers (observers) via their `update()` method.
83+
- The customers are informed about the sale and may choose to purchase the product if they have the budget.
84+
85+
## Summary of the `Observers` Directory
86+
87+
The **Observer** pattern is an essential part of this price-watching application. The design ensures that:
88+
- **Stores** act as the **subjects**, notifying **customers** (observers) when events like sales or restocks occur.
89+
- **Customers** respond to these notifications, updating their purchase decisions accordingly.
90+
91+
By using the Observer pattern, this directory demonstrates how stores can notify multiple customers about important events without the need for tight coupling between them. Customers can be added or removed from the notification list without affecting the store’s functionality.
92+
93+
This implementation highlights the advantages of the Observer pattern:
94+
- **Decoupling**: The store does not need to know anything about the customer’s behavior beyond notifying them of events. This reduces complexity and improves maintainability.
95+
- **Flexibility**: Multiple customers can observe a store simultaneously, and each customer can react differently to the same event (e.g., one customer may buy the product, while another may decide to wait for a better deal).
96+
- **Scalability**: New event types and customers can be added easily without changing the core logic of the stores.
97+
98+
By using the Observer pattern, this directory provides a simple, scalable, and modular implementation for a shopping trip simulation that tracks sales and customer behavior.

0 commit comments

Comments
 (0)