public abstract class Product {
public void commonMethod(){
System.out.println("产品是用来消费的");
}
abstract void name();
}
public class Computer extends Product {
@Override
void name() {
System.out.println("我是电脑");
}
}
public class Phone extends Product {
@Override
void name() {
System.out.println("我是手机");
}
}
public class Factory {
public <T extends Product> T createrProduct(Class<T> c) {
Product p = null;
try {
p = (Product) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
}
return (T) p;
}
}
class People{
public static void main(String[] args) {
Product computer = new Factory().createrProduct(Computer.class);
computer.commonMethod();
computer.name();
Product phone = new Factory().createrProduct(Phone.class);
phone.commonMethod();
phone.name();
}
}
输出:
产品是用来消费的
我是电脑
产品是用来消费的
我是手机
public class SingleProduct {
private SingleProduct(){}
}
public class SingleFactory {
private static SingleProduct sp;
static {
try {
Class c = Class.forName(sp.getClass().getName());
Constructor constructor = c.getDeclaredConstructor();
constructor.setAccessible(true);
sp = (SingleProduct) constructor.newInstance();
} catch (Exception e) {
}
}
public static SingleProduct getInstance(){
return sp;
}
}
class SinglePeople {
public static void main(String[] args) {
SingleProduct instance = SingleFactory.getInstance();
}
}
public abstract class AbstractFactory {
public abstract Product createProduct();
}
public class ComputerFactory extends AbstractFactory {
@Override
public Product createProduct() {
return new Computer();
}
}
public class PhoneFactory extends AbstractFactory{
@Override
public Product createProduct() {
return new Phone();
}
}
public class LazyProductFactory {
private static final Map<String, Product> map = new HashMap<>();
public synchronized Product createProduct(String type) {
Product p = null;
if (map.containsKey(type)) {
p = map.get(type);
} else {
if (type.equals("Computer")) {
p = new Computer();
}
if (type.equals("Phone")) {
p = new Phone();
}
map.put(type,p);
}
return p;
}
}