经常使用设计模式之工厂方法模式

工厂方法模式分为三种:普通工厂模式 多个工厂方法模式 静态工厂方法模式
1.一、普通工厂模式,就是创建一个工厂类,对实现了同一接口的产品类进行实例的建立测试

例子:
//发送短信和邮件的接口
public interface Sender {
  public void Send();
} 对象

//发送邮件的实现类
public class MailSender implements Sender {
  public void Send() {
    System.out.println("发送邮件!");
  }
}
//发送短信的实现类
public class SmsSender implements Sender {
  public void Send() {
    System.out.println("发送短信!");
  }
} 接口

//建立工厂类
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();
  }
} 产品


1.二、多个工厂方法模式 是对普通工厂方法模式的改进,在普通工厂方法模式中,若是传递的
字符串出错,则不能正确建立对象,而多个工厂方法模式是提供多个工厂方法,分别建立对象。class

//将上面的代码作下修改,改动下SendFactory类就行
//这个就不用根据用户传的字符串类建立对象了
public class SendFactory {

  public Sender produceMail(){
    return new MailSender();
  }

  public Sender produceSms(){
    return new SmsSender(); 方法

  }
}im

//测试类
public class FactoryTest {

  public static void main(String[] args) {
    SendFactory factory = new SendFactory();
    Sender sender = factory.produceMail();
    sender.Send();
  }
}static

 

1.三、静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的,不须要建立实例,直接调用便可(最经常使用)。mail

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();   } }

相关文章
相关标签/搜索