Algorithms and Data Structures/Data Structures

Object-Oriented Design

brightlightkim 2022. 6. 24. 14:46

How to approach:

 

Step 1: Handle Ambiguity

  • Ask:
    • Who is going to use it
    • How they are going to use it
    • Who, What, Where, When, How, and Why

 

Step 2: Define the Core Objects

  • Think about what the "core objects" in a system are

 

Step 3: Analyze Relationships

  • Ex: 
    • Party should have an array of Guests
    • Server and Host inherit from Employee
    • Each Table has one Party, but each Party may have multiple Tables
    • There is one Host for the Restaurant

Step 4: Investigate Actions

  • Basic Outline >> Consider the key actions that the objects will take and how they relate to each other.

 

 

Design Patterns

  • Singleton Class
    • Singleton patterns ensure that a class has only one instance and ensures access to the instance through the application. It can be useful in cases where you have a "global" object with exactly one instance
    • Many people dislike this pattern since it can interfere with unit testing
public class Restaurant {
	private static Restaurant _instance = null;
    protected Restaurant() {...}
    public static Restaurant getInstance() {
    	if (_instance == null) {
        	_instance = new Restaurant();
        }
    }
}
  • Factory Method
    • Offers an interface for creating an instance of a class, which its subclasses decide which class to instantiate. You might want to implement this with the creator class being abstract and not providing an implementation for the Factory method. Or, you could have the Creator class be a concrete class that provides an implementation for the Factory method. In this case, the Factory method would take a parameter representing which class to instantiate.
public class CardGame {
    public static CardGame createCardGame(GameType type) {
        if (type == GameType.Poker) {
            return new PokerGame();
        }   else if (type == GameType.BlackJack){
            return new BlackJackGame();
        }
        return null;
    }
}