分别使用工厂模式,单例模式,构建者模式创建一个Integer对象
时间: 2023-02-20 09:21:21 浏览: 85
javascript工厂模式和构造函数模式创建对象方法解析
工厂模式:
```
public interface IntegerFactory {
Integer createInteger(int value);
}
public class ConcreteIntegerFactory implements IntegerFactory {
@Override
public Integer createInteger(int value) {
return new Integer(value);
}
}
IntegerFactory factory = new ConcreteIntegerFactory();
Integer integer = factory.createInteger(5);
```
单例模式:
```
public class IntegerSingleton {
private static final IntegerSingleton INSTANCE = new IntegerSingleton();
private final Integer value;
private IntegerSingleton() {
value = new Integer(5);
}
public static IntegerSingleton getInstance() {
return INSTANCE;
}
public Integer getValue() {
return value;
}
}
IntegerSingleton singleton = IntegerSingleton.getInstance();
Integer integer = singleton.getValue();
```
构建者模式:
```
public class IntegerBuilder {
private final int value;
private IntegerBuilder(int value) {
this.value = value;
}
public static class Builder {
private int value;
public Builder setValue(int value) {
this.value = value;
return this;
}
public IntegerBuilder build() {
return new IntegerBuilder(value);
}
}
public Integer getValue() {
return new Integer(value);
}
}
IntegerBuilder builder = new IntegerBuilder.Builder().setValue(5).build();
Integer integer = builder.getValue();
```
阅读全文