4. 静态工厂方法
静态工厂方法模式,将多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可

// 定义一个接口
public interface Sender{
void send();
}
// 定义一个实现类
public class MailSender implements Sender{
@Override
public void send(){
System.out.println("发生邮件");
}
// 定义一个短息实现类
public class SmsSender implements Sender{
@Override
public void send(){
System.out.println("发送短信");
}
//定义一个工厂类
public class SendFactory{
public static Send getMail(){
return new MailSender();
}
public static Send getSms(){
return new SmsSender();
}
}
//测试
public class FactoryTest{
public static void main(String[] args){
Sender mailSender = SendFactory .getMail();
mailSender.send();
Sender smsSender = SendFactory .getSms();
smsSender.send();
}
}
工厂模式适合:凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建

浙公网安备 33010602011771号