设计模式(Design Pattern) - 创建型模式(Creational Pattern) - 抽象工厂模式(Abstract Factory) - Java实现

时间:2022-09-08 20:05:23

设计模式(Design Pattern) - 创建型模式(Creational Pattern) - 抽象工厂模式(Abstract Factory)
比工厂模式更抽象的方法,效果:增加功能不必需改历史代码。

1、说明:
(1)Sender 接口;(同工厂模式)
(2)MailSender 实现类;(同工厂模式)
(3)SmsSender 实现类;(同工厂模式)
(4)Factory 工厂.接口;
(5)MailFactory 工厂实现类;
(6)SmsFactory 工厂实现类。

2、Java实现,代码如下:
(1)Sender

package com.java.designPattern.abastractFactory;

/**
* 接口
*
*/

public interface Sender {

public void send();

}

(2)MailSender

package com.java.designPattern.abastractFactory;

/**
* 实现类
*
*/

public class MailSender implements Sender {

@Override
public void send() {
System.out.println("mail send !");
}

}

(3)SmsSender

package com.java.designPattern.abastractFactory;

/**
* 实现类
*
*/

public class SmsSender implements Sender {

@Override
public void send() {
System.out.println("sms send !");
}

}

(4)Factory

package com.java.designPattern.abastractFactory;

/**
* 抽象工厂
*
*/

public interface Factory {

public Sender produce();

}

(5)MailFactory

package com.java.designPattern.abastractFactory;

/**
* 工厂实现类
*
*/

public class MailFactory implements Factory {

@Override
public Sender produce() {
return new MailSender();
}

}

(6)SmsFactory

package com.java.designPattern.abastractFactory;

/**
* 工厂实现类
*
*/

public class SmsFactory implements Factory {

@Override
public Sender produce() {
return new SmsSender();
}

}

(7)Test

package com.java.designPattern.abastractFactory;

/**
* 测试类
*
*/

public class Test {

public static void main(String[] args) {
Factory mailFactory = new MailFactory();
Sender mailSender = mailFactory.produce();
mailSender.send();

Factory smsFactory = new SmsFactory();
Sender smsSender = smsFactory.produce();
smsSender.send();
}

}

输出:
mail send !
sms send !