java常用设计模式

06 Sep 2016, by

设计模式总结

工厂模式(创建时将声明类型抽象, 用工厂统一管理)

创建接口:
public interface Sender {  
    public void Send();  
} 
实现接口的类:
public class SmsSender implements Sender {  
    @Override  
    public void Send() {  
        System.out.println("this is sms sender!");  
    }  
}  
public class MailSender implements Sender {  
    @Override  
    public void Send() {  
        System.out.println("this is mailsender!");  
    }  
}  
创建工厂:
public class SendFactory {  
    public static Sender produceMail(){  
        return new MailSender();  
    }  
    public static Sender produceSms(){  
        return new SmsSender();  
    }  
} 
使用:
public class FactoryTest {
    public static void main(String[] args) {      
        Sender sender = SendFactory.produceMail();  
        sender.Send();  
    }
} 

抽象工厂模式