- 简单工厂和静态工厂模式
- 流程:定义接口——>定义接口的实现类——>定义工厂生产产品
public interface Sender {
void send();
}
public class MailSender implements Sender {
@Override
public void send() {
System.out.println("this is mail sender");
}
}
public class SmsSender implements Sender {
@Override
public void send() {
System.out.println("this is Sms sender");
}
}
class SendFactory {
/**
* 静态工厂的方法
*
* @return
*/
static MailSender getMailSender() {
return new MailSender();
}
/**
* 静态工厂的方法
*
* @return
*/
static SmsSender getSmsSender() {
return new SmsSender();
}
/**
* 普通工厂的方法
*
* @param type
* @return
*/
Sender produce(String type) {
switch (type) {
case "mail":
return new MailSender();
case "sms":
return new SmsSender();
default:
return null;
}
}
}
public class FactoryTest {
public static void main(String args[]) {
//普通工厂
SendFactory factory = new SendFactory();
Sender sms = factory.produce("sms");
sms.send();
System.out.println("----------------");
Sender mail = factory.produce("mail");
mail.send();
//静态工厂
MailSender mailSender = SendFactory.getMailSender();
mailSender.send();
SmsSender smsSender = SendFactory.getSmsSender();
smsSender.send();
}
}
- 抽象工厂模式
- 流程:定义方法接口——>定义方法接口的实现类——>定义工厂类接口——>定义工厂类
public interface Sender {
void send();
}
public class MailSender implements Sender {
@Override
public void send() {
System.out.println("this is mail sender");
}
}
public class SmsSender implements Sender{
@Override
public void send() {
System.out.println("this is sms sender");
}
}
public interface Provider {
Sender produce();
}
public class MailFactory implements Provider {
@Override
public Sender produce() {
return new MailSender();
}
}
public class SmsFactory implements Provider {
@Override
public Sender produce() {
return new SmsSender();
}
}
public class AbsFactoryTest {
public static void main(String args[]) {
Provider smsProvider = new SmsFactory();
Sender smsProduce = smsProvider.produce();
smsProduce.send();
//也可以
smsProvider.produce().send();
Provider mailProvider = new MailFactory();
Sender mailProduce = mailProvider.produce();
mailProduce.send();
//也可以
mailProvider.produce().send();
}
}
建议用抽象工厂模式,便于以后的拓展