類(lèi)圖如下:
代碼示例如下:
public class AbstractFactory {
public static void main(String[] args) {
SenderFactory senderFactory = new MailSenderFactory();
Sender sender = senderFactory.produce();
sender.send();
}
}
interface Sender {
public void send();
}
class MailSender implements Sender {
public void send() {
System.out.println("Send by mail");
}
}
class SmsSender implements Sender {
public void send() {
System.out.println("Send by sms");
}
}
interface SenderFactory {
Sender produce();
}
class MailSenderFactory implements SenderFactory {
public Sender produce() {
return new MailSender();
}
}
class SmsSenderFactory implements SenderFactory {
public Sender produce() {
return new SmsSender();
}
}