凡是出现了大量的实例需要创建,而且具有共同的接口时,可以通过工厂方法模式进行创建。
一个接口: Sender
public interface Sender{ public void send(); }
两个实现类: MainSender和SmsSender
public class MailSender implements Sender{ @Override public void send(){ System.out.println("Main Send..."); } }
public class SmsSender implements Sender{ @Override public void send(){ System.out.println("Sms Send..."); } }
一个接口: Provider
public interface Provider{ public Sender produce(); }
两个实现类: MainFactory和SmsFactory
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 TestDemo{ @Test public void testFactory(){ Provider provider = new MailFactory(); Sender sender = provider.produce(); sender.send(); } }结果:
Main Send...