Patterns
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
Factory
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for “manufacturing” an object. A Parameterized Factory receives the name of the class to instantiate as argument.
Singleton
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
Dùng khi:
– Bạn không muốn kế thừa class cha.
– Bạn không muốn hao tốn resource khi phải tạo ra nhiều đối tượng (object)
– Bạn không thích reference tới object đó (vì dù muốn dù không bạn cũng phải tạo đối tượng qua từ khóa new rồi mới xài nó được.)
– Điều hành lớp qua phương thức static. Chỉ cho phép ta tạo một đối tượng duy nhất.