Simple factory pattern example of java interface oriented programming

This paper illustrates the simple factory pattern of java interface oriented programming. Share with you for your reference, as follows:

One code

interface Output
{
  // 接口里定义的成员变量只能是常量
  int MAX_CACHE_LINE = 50;
  // 接口里定义的普通方法只能是public的抽象方法
  void out();
  void getData( String msg );
}
class Printer implements Output {
  private String[] printData
      = new String[MAX_CACHE_LINE];
  // 用以记录当前需打印的作业数
  private int datanum = 0;
  public void out() {
    // 只要还有作业,继续打印
    while (datanum > 0) {
      System.out.println("打印机打印:" + printData[0]);
      // 把作业队列整体前移一位,并将剩下的作业数减1
      System.arraycopy(printData,1,printData,--datanum);
    }
  }
  public void getData( String msg ) {
    if (datanum >= MAX_CACHE_LINE) {
      System.out.println("输出队列已满,添加失败");
    } else {
      // 把打印数据添加到队列里,已保存数据的数量加1。
      printData[datanum++] = msg;
    }
  }
}
class BetterPrinter implements Output
{
  private String[] printData
      = new String[MAX_CACHE_LINE * 2];
  // 用以记录当前需打印的作业数
  private int datanum = 0;
  public void out()
  {
    // 只要还有作业,继续打印
    while(datanum > 0)
    {
      System.out.println("高速打印机正在打印:" + printData[0]);
      // 把作业队列整体前移一位,并将剩下的作业数减1
      System.arraycopy(printData,--datanum);
    }
  }
  public void getData(String msg)
  {
    if (datanum >= MAX_CACHE_LINE * 2)
    {
      System.out.println("输出队列已满,添加失败");
    }
    else
    {
      // 把打印数据添加到队列里,已保存数据的数量加1。
      printData[datanum++] = msg;
    }
  }
}
class Computer
{
  private Output out;
  public Computer(Output out)
  {
   this.out = out;
  }
  // 定义一个模拟获取字符串输入的方法
  public void keyIn(String msg)
  {
   out.getData(msg);
  }
  // 定义一个模拟打印的方法
  public void print()
  {
   out.out();
  }
}
public class OutputFactory
{
  public Output getOutput()
  {
//  return new Printer();
    return new BetterPrinter();
  }
  public static void main(String[] args)
  {
    OutputFactory of = new OutputFactory();
    Computer c = new Computer(of.getOutput());
    c.keyIn("轻量级Java EE企业应用实战");
    c.keyIn("疯狂Java讲义");
    c.print();
  }
}

II. Operation

Three kinds of Graphs

For more Java related content, interested readers can view the special topics of this site: introduction and advanced tutorial of java object-oriented programming, tutorial of Java data structure and algorithm, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills

I hope this article will be helpful to you in Java programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>