标签:调用 interface line 返回 abs 不同的 bst ctf block
构造方法私有
存在由static修饰的返回实例的方法
减少创建Java实例所带来的系统开销
便于系统跟踪单个Java实例的声明周期、实例状态等
package singleton;
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
通过工厂类的形式进行解耦合
依赖关系通过接口解耦合
让对象的调用者和对象创建过程分离,当对象调用者需要对象时,直接向工厂请求即可;
避免了对象的调用者和对象的实现类以硬解码方式耦合,提高了系统的可维护性、拓展性
需要注意的一个陷阱是:当产品修改时,工厂类也要做相应的修改
package simplefactory;
public 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();
}
}
package simplefactory;
public class OutputFactory {
public Output getOutput() {
return new Printer();
}
}
package simplefactory;
public interface Output {
final int MAX_CACHE_LINE=200;
void getData(String msg);
void out();
}
package simplefactory;
public class Printer implements Output {
private String[] printData = new String[MAX_CACHE_LINE];
private int dataNum = 0;
@Override
public void getData(String msg) {
if(dataNum >= MAX_CACHE_LINE) {
System.out.println("输出队列已满,添加失败");
} else {
printData[dataNum++] = msg;
}
}
@Override
public void out() {
while(dataNum > 0) {
System.out.println("打印机打印:" + printData[0]);
System.arraycopy(printData, 1, printData, 0, --dataNum);
}
}
}
package simplefactory;
public class Test {
public static void main(String[] args) {
OutputFactory of = new OutputFactory();
Computer c = new Computer(of.getOutput());
c.keyIn("hello world");
c.keyIn("java");
c.keyIn("spring");
c.print();
}
}
// 工厂接口
package abstractfactory;
import simplefactory.Output;
/**
*
*TODO output工厂接口
*
* @author CaoLei 2018年7月1日下午3:19:36
* OutputFactory
*/
public interface OutputFactory {
Output getOutput();
}
// 工厂方法,工厂类
package abstractfactory;
import simplefactory.BetterPrinter;
import simplefactory.Output;
public class BetterPrinterFactory implements OutputFactory {
@Override
public Output getOutput() {
return new BetterPrinter();
}
}
// 抽象工厂,抽象工厂类
package abstractfactory;
public class OutputFactoryFactory {
public static OutputFactory getOutputFactory(String type) {
if ("better".equals(type)) {
return new BetterPrinterFactory();
} else {
return new PrinterFactory();
}
}
}
标签:调用 interface line 返回 abs 不同的 bst ctf block
原文地址:https://www.cnblogs.com/caoleiCoding/p/9251295.html