举例如下:(我们举一个发送邮件和短信的例子)
首先,创建二者的共同接口:
[java] view plaincopy
public interface Sender {
public void Send();
}
其次,创建实现类:
[java] view plaincopy
public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mailsender!");
}
}
[java] view plaincopy
public class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
最后,建工厂类:
[java] view plaincopy
public class SendFactory {
public Sender produce(String type) {
if ("mail".equals(type)) {
return new MailSender();
} else if ("sms".equals(type)) {
return new SmsSender();
} else {
System.out.println("请输入正确的类型!");
return null;
}
}
}
我们来测试下:
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produce("sms");
sender.Send();
}
}
输出:this is sms sender!