设计模式之【抽象工厂模式--Factory】

原则:依赖倒转原则:针对接口编程,依赖于抽象而不依赖于具体;

一、创建接口:发送消息

package Factory;

public interface Sender{
    public void Send();

}

二、创建两个实现类

1、发送邮箱

package Factory;

public class MailSend implements Sender{
    
    @Override
    public void Send() {
        System.out.println("mailsend");
        
    }

}

 

2、发送短信

package Factory;

public class SMSSend implements Sender{

    @Override
    public void Send() {
        // TODO Auto-generated method stub
        System.out.println("SMSSender");
    }

}

三、创建工厂类

package Factory;

public class Sendfactory {
    public Sender produce(String type){
        if("mail".equals(type)){
            return new MailSend();
        }else if("sms".equals(type)){
            return new SMSSend();
        }else{
            System.out.println("请输入正确参数");
            return null;
        }
    }

}

四、应用场景类

package Factory;

public class FactoryTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Sendfactory factory = new Sendfactory();
        Sender send = factory.produce("sms");
        send.Send();
    }

}

 五、结果

SMSSender

 

posted @ 2015-07-24 15:27  张平a  阅读(155)  评论(0编辑  收藏  举报