简单工厂模式
1. 定义一个接口
public interface Sender {
public void Send();
}
2. 创建实现类
// 创建发送邮件实现类
public class MailSender implements Sender{
public void Send(){
System.out.println("This is MailSender.");
}
}
// 创建发送短信实现类
public class MessageSender implements Sender{
public void Send(){
System.out.println("This is MessageSend.");
}
}
3. 创建工厂
public class SendFactory {
public Sender produceMail(){
return new MailSender();
}
public Sender produceMessage(){
return new MessageSender();
}
// 一般不采用这种方式,用上面两种方式比较好
public Sender produce(String type){
if("mail".equals(type)){
return new MailSender();
} else if ("message".equals(type)){
return new MessageSender();
} else {
System.out.println("Please input the right type.");
return null;
}
}
}
4. 主测试函数实现
public class FactoryTest {
public static void tmain(String[] args){
SendFactory factory1 = new SendFactory();
Sender sender1 = factory1.produce("mail");
sender1.Send();
SendFactory factory2 = new SendFactory();
Sender sender2 = factory2.produceMail();
sender2.Send();
}
}
抽象工厂模式
1. 创建接口
public interface Sender {
public void Send();
}
2. 创建实现类
public class SendMailFactory {
public Sender procedure(){
return new MailSender();
}
}
public class MessageSender implements Sender{
public void Send(){
System.out.println("This is MessageSender.");
}
}
3. 创建工厂
public class SendMailFactory {
public Sender procedure(){
return new MailSender();
}
}
public class SendMessageFactory {
public Sender procedure(){
return new MessageSender();
}
}
4. 再提供一个接口
public interface Provider {
public Sender procedure();
}
5. 主测试函数
public class Test {
public static void main(String[] args){
System.out.println("The abstract factory begins.");
SendMailFactory provider = new SendMailFactory();
Sender sender = provider.procedure();
sender.Send();
System.out.println("The abstract factory is over.");
}
}
参考链接:
http://blog.csdn.net/a394268045/article/details/51801258