0

[Design Patterns] Factory Pattern

1. Factory Method Pattern là gì?

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

  • Factory Pattern cung cấp một Interface đại điện cho các instance trả về
  • Subclass có thể lựa chọn implementation của Interface này
  • Thường sẽ có dạng NotiferFactory.getNotifier(NotifierType.TELEGRAM)

2. Cách Implement

2.1. Define Interface

public interface Notifier {
    void notify(String message);
}

2.2. Implement Interface

public class Slack implements Notifier {
    @Override
    public void notify(String message) {
        System.out.println("[Slack] " + message);
    }
}
public class Telegram implements Notifier{
    @Override
    public void notify(String message) {
        System.out.println("[Telegram] " + message);
    }
}

2.3. Define Types

public enum NotifierType {
    SLACK,
    TELEGRAM
}

2.4. Factory

public class NotifierFactory {
    public static Notifier getNotifier(NotifierType type) throws IllegalArgumentException {
        return switch (type) {
            case SLACK -> new Slack();
            case TELEGRAM -> new Telegram();
        };
    }
}

3. Real-world example

  • Notifier with multiple channels
  • NumberFormat.getInstance(Locale inLocale)
  • Calendar.getInstance(Locale aLocale)
  • Calendar.getInstance(TimeZone zone)

4. Pros & Cons

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí