简单工厂模式实例

来源:互联网 发布:老外在中国 知乎 编辑:程序博客网 时间:2024/04/29 13:46

         类的的实例对象交由工厂来生成的设计方式就是简单的工程设计模式。Spring的IOC就是一个超级工厂。下面我以计算机拥有打印机为实例进行阐述简单工程模式的实现。计算机需要普通的打印机或者带缓存的打印机直接交给工厂来实现。

 

1. 打印机的输出接口

package com.lanp.factory;

/**
 * 输出接口
 * @author LanP
 */
public interface Output {
 /**
  * 获取输出消息
  * @param msg
  * @return String
  */
 String getMsg(String msg);
 
 void out();
}

2. 普通打印机

package com.lanp.factory;

/**
 * 普通打印机类,实现了输出接口
 * @author LanP
 */
public class Printer implements Output {
 
 private static final int MAX_SIZE = 1024;
 private String[] printMsg = new String[MAX_SIZE];
 /**
  * 记录当前打印的作用位置
  */
 private int msgNum = 0;
 
 
 @Override
 public String getMsg(String msg) {
  if(msgNum >= MAX_SIZE){
   System.out.println("输出管道队列已满,添加失败!");
  } else {
   printMsg[msgNum++] = msg;
  }
   
  return msg;
 }

 @Override
 public void out() {
  //只要尚有作用没有打印就继续打印
  while(msgNum > 0) {
   System.out.println("普通打印机打印: " + printMsg[0]);
   //将作业队列向前移一位,剩下的作业书量减一
   System.arraycopy(printMsg, 1, printMsg, 0, --msgNum);
  }
 }
 
}

3. 带缓存的打印机

package com.lanp.factory;

/**
 * 带缓存的打印机
 * @author LanP
 */
public class BuffPrinter implements Output {
 
 private static final int MAX_SIZE = 1024;
 private StringBuffer[] printMsg = new StringBuffer[MAX_SIZE * 2];
 /**
  * 记录当前打印的作用位置
  */
 private int msgNum = 0;
 
 
 @Override
 public String getMsg(String msg) {
  if(msgNum >= MAX_SIZE){
   System.out.println("输出管道队列已满,添加失败!");
  } else {
   printMsg[msgNum++] = new StringBuffer(msg);
  }
   
  return msg;
 }

 @Override
 public void out() {
  //只要尚有作用没有打印就继续打印
  while(msgNum > 0) {
   System.out.println("缓存打印机打印: " + printMsg[0].toString());
   //将作业队列向前移一位,剩下的作业书量减一
   System.arraycopy(printMsg, 1, printMsg, 0, --msgNum);
  }
 }
 
}

4. 打印机工厂

package com.lanp.factory;

public class OutputFactory {
 public Output getOutput(String output) {
  if(null != output) {
   if(output.toLowerCase().equals("printer")) {
    return new Printer();
   } else {
    return new BuffPrinter();
   }
  } else {
   return null;
  }
 }
}

5.计算机

package com.lanp.factory;

/**
 * 计算机实例,具有打印机
 * @author LanP
 * @version V1.0
 */
public class Computer {
 private Output output;
 
 public Computer(Output output) {
  this.output = output;
 }
 
 /**
  * 模拟消息输入的方法
  * @param msg
  */
 public void msgIn(String msg) {
  this.output.getMsg(msg);
 }
 
 /**
  * 模拟打印
  */
 public void print() {
  output.out();
 }
 
 /**
  * 程序的入口方法,用于测试
  * @param args
  */
 public static void main(String[] args) {
  Computer computer = new Computer(new OutputFactory().getOutput("printer"));
  computer.msgIn("飘飘9");
  computer.msgIn("飘飘99");
  computer.print();
 }

}

 

原创粉丝点击