package com.sheting.design.pattern.demo1;
public abstract class Computer {
public abstract String getRAM();
public abstract String getHDD();
public abstract String getCPU();
@Override
public String toString(){
return "RAM= "+this.getRAM()+", HDD="+this.getHDD()+", CPU="+this.getCPU();
}
}
package com.sheting.design.pattern.demo1;
public class PC extends Computer {
private String ram;
private String hdd;
private String cpu;
public PC(String ram, String hdd, String cpu) {
this.ram = ram;
this.hdd = hdd;
this.cpu = cpu;
}
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
package com.sheting.design.pattern.demo1;
public class Server extends Computer {
private String ram;
private String hdd;
private String cpu;
public Server(String ram, String hdd, String cpu) {
this.ram = ram;
this.hdd = hdd;
this.cpu = cpu;
}
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
package com.sheting.design.pattern.demo1;
public class ComputerFactory {
public static Computer getComputer(String type, String ram, String hdd, String cpu) {
if ("PC".equalsIgnoreCase(type)) {
return new PC(ram, hdd, cpu);
} else if ("Server".equalsIgnoreCase(type)) {
return new Server(ram, hdd, cpu);
}
return null;
}
}
package com.sheting.design.pattern.demo1;
public class TestFactory {
public static void main(String[] args) {
Computer pc = ComputerFactory.getComputer("pc", "2 GB", "500 GB", "2.4 GHz");
Computer server = ComputerFactory.getComputer("server", "16 GB", "1 TB", "2.9 GHz");
System.out.println("Factory PC Config::" + pc);
System.out.println("Factory Server Config::" + server);
}
}
JDK中的工厂方法模式
1. java.text.NumberFormat
private static NumberFormat getInstance(LocaleProviderAdapter adapter,
Locale locale, int choice) {
NumberFormatProvider provider = adapter.getNumberFormatProvider();
NumberFormat numberFormat = null;
switch (choice) {
case NUMBERSTYLE:
numberFormat = provider.getNumberInstance(locale);
break;
case PERCENTSTYLE:
numberFormat = provider.getPercentInstance(locale);
break;
case CURRENCYSTYLE:
numberFormat = provider.getCurrencyInstance(locale);
break;
case INTEGERSTYLE:
numberFormat = provider.getIntegerInstance(locale);
break;
}
return numberFormat;
}
2. 包装类中的valueOf()
java.lang.Integer
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}