OOP Design

OOD 可以看成是 High Level System Design 后的具体实现。

This blog is for Object Oriented Design, please revisit frequently to refresh. The notes are mainly from https://www.educative.io/.

OOP Design video OOP: Object-oriented programming Design pattern: singleton, factory, etc Concurrency

The four principles of object-oriented programming are encapsulation, abstraction, inheritance, and polymorphism.

The process of OO analysis and design can be described as:

  1. Identifying the objects in a system;
  2. Defining relationships between objects;
  3. Establishing the interface of each object;
  4. Making a design, which can be converted to executables using OO languages.

要清楚如何定义enum, constants abstract class, interface. 如何选择他们.

UML stands for Unified Modeling Language and is used to model the Object-Oriented Analysis of a software system. UML is a way of visualizing and documenting a software system by using a collection of diagrams.

Be familiar with:

  1. use case diagram (actors, 不是指所有的object: admin, customer, system…)
  2. class diagram (relationships)
  3. sequence diagram (emphasize on interaction between objects, time series)
  4. activity diagram (emphasize on control of flow)

Summary: 总的来看,通过class diagram,设计好基本的abstract class, interface, base class,然后再延伸,实例化。实例化的class中设计好attributes, method的实现。

  • 定义好enum, constants.

  • 把不同的系统分开设计,比如notifiation, payment…

  • 对于actor people,有一个account class, 被包含在person abstract class中,然后这个person被实例化为其他诸如guest, admin, member等class. (有类似关系的以此类推)

  • 对于有查询需求的任务, search interface中声明search方法,然后被search的对象类implements, 在这个对象内部实现search的各种method, 通常需要与database连接。

  • 可能会用到设计模式

Design a Library Management System

Library management systems help libraries keep track of the books and their checkouts, as well as members’ subscriptions and profiles.

  1. get clarity of the requirements, Be sure to ask questions to find the exact scope of the system that the interviewer has in mind

找到actors之后,围绕actors就可以提出具体要求,可以做什么事情: member can search book by title, name, date, category, author. book has unique id, rack number, etc. member can checkout, reserve book copies. days a member can keep the book. numbers a member can checkout. collect fine if after due date. system can send notification to user. …

最后确认需具体要实现什么的功能?

  1. use case diagram, define top use cases 从object角度, 看看各自可以有什么操作, 对具体的实现功能,画出具体的use case diagram。

  2. class diagram 有几个问题: 要从high level考虑有哪些abstract class, enum, constant, interface等。 然后各自的依赖关系画一下。

interface vs inheritace,什么时候谁合适?

在实现代码的时候,class diagram可以作为指导原则

  1. activity diagram 画出具体实现某一功能的状态图

  2. code Since you are not required to write a fully executable code in an interview, you can assume parts of the code to interact with the database, payment system, etc…

主要写出基本的部分: Enums and Constants:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// enums
public enum BookStatus
{
AVAILABLE,
RESERVED,
LOANED,
LOST
}

public enum ReservationStatus
{
WAITING,
PENDING,
CANCELED,
NONE
}
// constants
public class Constants {
public static final int MAX_BOOKS_ISSUED_TO_A_USER = 5;
public static final int MAX_LENDING_DAYS = 10;
}

然后是abstrace class, interface 和其他继承,实现的类,根据class diagram去实现,举几个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// For simplicity, we are not defining getter and setter functions. The reader can
// assume that all class attributes are private and accessed through their respective
// public getter methods and modified only through their public methods function.
public abstract class Book {
private String ISBN;
private String title;
private String subject;
private String publisher;
private String language;
private int numberOfPages;
private List<Author> authors;
}

public class BookItem extends Book {
private String barcode;
private boolean isReferenceOnly;
private Date borrowed;
private Date dueDate;
private double price;
private BookFormat format;
private BookStatus status;
private Date dateOfPurchase;
private Date publicationDate;
private Rack placedAt;

public boolean checkout(String memberId) {
if(bookItem.getIsReferenceOnly()) {
ShowError("This book is Reference only and can't be issued");
return false;
}
if(!BookLending.lendBook(this.getBarCode(), memberId)){
return false;
}
this.updateBookItemStatus(BookStatus.LOANED);
return true;
}
}

public class Rack {
private int number;
private String locationIdentifier;
}

// interface
public interface Search
{
public List<Book> searchByTitle(String title);
public List<Book> searchByAuthor(String author);
public List<Book> searchBySubject(String subject);
public List<Book> searchByPubDate(Date publishDate);
}

public class Catalog implements Search
{
private HashMap<String, List<Book>> bookTitles;
private HashMap<String, List<Book>> bookAuthors;
private HashMap<String, List<Book>> bookSubjects;
private HashMap<String, List<Book>> bookPublicationDates;

public List<Book> searchByTitle(String query) {
// return all books containing the string query in their title.
return bookTitles.get(query);
}

public List<Book> searchByAuthor(String query) {
// return all books containing the string query in their author's name.
return bookAuthors.get(query);
}
}

Design parking lot

https://www.youtube.com/watch?v=DSGsa0pu8-k&t=814s 评论里有一些批评意见,可以参考。

  • Identify the problem scope: do you want me to come up a system design, or class hierarchy? or should we get into certain specific question and wirte some methods?

  • How you approach the problem: show a clear and systematic approach how you tackle this problem how is the parking lot designed? building? open space? free or pay? how many spots are we talking about? floors? are there mutliple entrances or exits? should we first fill out floor from top? prices strategy? premium, general customer?

进口的识别系统会识别plate number + vehicle type,然后再ticket上标明应该停放到哪个building,哪一层的哪个位置。(如果有多个entrance, 则有concurrency问题需要解决)

code some part of the design? which part do you want me to implement? We have database backend but here for Simplicity can we assume we store the data in memory?

算法去实现spot -> vehicle的分配。

  1. system requirements multi-floors multi-entries or exits parking ticket pay cash or credit card pay at info panel or at exit display message when full different parking spots for different type car electric car spots, charge station support step price hourly

  2. use case diagram get clarity what functions we need to implement.

  3. class diagram ParkingLot ParkingFloor ParkingSpot Account: admin and parking attendant ParkingTicket Vehicle: many types Payment: credit card or cash ParkingRate ParkingDisplayBoard ParkingAttendantPortal CustomerInfoPortal ElectricPanel

  4. code see: https://www.educative.io/courses/grokking-the-object-oriented-design-interview/gxM3gRxmr8Z

Design Amazon online shopping system

  1. get clarity
  • what scope do you want me to focus on?
  • high level design or dive into a specific function component, wirte class and method.

Objects: guest, member, admin and system 分别讨论一下各自可以做什么操作。

几个主要的system: register, search, review, order, shipment, payment, notification.

  1. use case diagram
  2. activity diagram
  3. sequence diagram

Design shopify

shopify eCommerce platform 类似于淘宝, 有自己的网店portal.

Design stack overflow

Stack Overflow is one of the largest online communities for developers to learn and share their knowledge.

Users of Stack Overflow can earn reputation points and badges. For example, a person is awarded ten reputation points for receiving an “up” vote on an answer and five points for the “up” vote of a question. The can also receive badges for their valued contributions. A higher reputation lets users unlock new privileges like the ability to vote, comment on, and even edit other people’s posts.

Actors: admin, guest, member, system, moderator(close,delete,undelete question)

Design a Movie Ticket Booking System

  1. high level overview movie theater -> halls -> moive -> shows search movie select show and boot ticket select seat notification payment concurrency issue when booking: 在数据库层面实现的,没有使用Java的concurrency package We can use transactions in SQL databases to avoid any clashes. lock the rows before we update them discount/coupon apply

  2. use case diagram

  3. class diagram

  4. activity diagram

Design ATM

Automated teller machine (ATM) withdraw and deposit money

components of ATM: card reader kaypad screen Cash dispenser Deposit slot printer network

checking and saving account of user 都放在transaction中,保证原子性: Balance inquiry Deposit cash Deposit check Withdraw cash Transfer funds

The ATM will maintain an internal log of transactions that contains information about hardware failures; this log will be used by the ATM operator to resolve any issues.

actors: operator customer bank manager system

Design an Airline Management System

This system involves the scheduling of flights, air ticket reservations, flight cancellations, customer support, and staff management. Daily flights updates can also be retrieved by using the system.

roundtrip one way mutli-city

回忆一下预定的界面 departing returning

Design a Hotel Management System

和ticket booking类似 a online portal, keep track of available rooms, book rooms and generate bill. booking of different room types like standard, deluxe, family suite, etc housekeeping log to keep track of all housekeeping tasks

  1. use case diagram guest manager system housekeeper Receptionist

  2. class diagram

  3. activity diagram

Restaurant Management system

同上,补充几个特点: The system allows the manager to keep track of available tables in the system as well as the reservation of tables and bill generation. 这里是西餐的形式,没人一个座位,单独点餐。

menu -> menu sections -> items rooms -> tables (reservation or walk-in)

Design Facebook

Facebook is an online social networking service where users can connect with other users to post and read messages. Users access Facebook through their website interface or mobile apps.

Design LinkedIn

Similar to Facebook design but carter to professionals. 各种功能几乎就一样。

A LinkedIn member’s profile page, which emphasizes their skills, employment history, and education, has professional network news feeds with customizable modules.

  1. use case diagram member admin system

  2. class diagram

  3. activity diagram

0%