创建型模式之工厂方法模式
定义:Define an interface for creating an object,but let subclasses decide which class to instantiate . Factory Method lets a class defer instantiation to subclasses .
定义一个用于创建对象的借口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
例子:现有手机,手机分为:IPhone,Android Phone两种,使用工厂方法模式,实现产生手机对象。
工厂:
public abstract class AbstractPhoneFactory {
public abstract <T extends Phone> T creatPhone(Class<T> c);
}
工厂的实现类:
public class PhoneFactory extends AbstractPhoneFactory {
@Override
public <T extends Phone> T creatPhone(Class<T> c) {
try {
T p = (T) Class.forName(c.getName()).newInstance();
return p;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
手机:
public abstract class Phone {
public Phone(){
System.out.println("this is a Phone");
}
public abstract void ring();
public abstract void inComingPhone();
public abstract void outGoingPhone();
}
IPhone,APhone:
public class IPhone extends Phone {
public IPhone(){
System.out.println("--I'm IPhone --");
}
@Override
public void ring() {
System.out.println("--I'm IPhone --ring");
}
@Override
public void inComingPhone() {
System.out.println("--I'm IPhone --inComingPhone");
}
@Override
public void outGoingPhone() {
System.out.println("--I'm IPhone --outGoingPhone");
}
}
public class APhone extends Phone {
public APhone(){
System.out.println("-- I'm Android Phone --");
}
@Override
public void ring() {
System.out.println("-- I'm Android Phone --ring");
}
@Override
public void inComingPhone() {
System.out.println("-- I'm Android Phone --inComingPhone");
}
@Override
public void outGoingPhone() {
System.out.println("-- I'm Android Phone --outGoingPhone");
}
}
测试类:
public class MainClass {
public static void main(String[] args) {
PhoneFactory factory = new PhoneFactory();
IPhone iphone = factory.creatPhone(IPhone.class);
iphone.ring();
iphone.inComingPhone();
iphone.outGoingPhone();
System.out.println("\n\n");
APhone aphone = factory.creatPhone(APhone.class);
aphone.ring();
aphone.inComingPhone();
aphone.outGoingPhone();
}
}
---------------------------------------------------- 誑逩の蝸犇 : Nothing is impossible. ----------------------------------------------------