简单工厂模式
This commit is contained in:
@ -0,0 +1,8 @@
|
||||
package com.heibaiying.creational.SimpleFactory;
|
||||
|
||||
|
||||
public class HuaweiPhone extends Phone {
|
||||
public void call(String phoneNum) {
|
||||
System.out.println("华为手机拨打电话:" + phoneNum);
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.heibaiying.creational.SimpleFactory;
|
||||
|
||||
/**
|
||||
* 手机
|
||||
*/
|
||||
public abstract class Phone {
|
||||
public abstract void call(String phoneNum);
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.heibaiying.creational.SimpleFactory;
|
||||
|
||||
|
||||
public class PhoneFactory {
|
||||
|
||||
public Phone getPhone(String type) {
|
||||
if ("xiaomi".equalsIgnoreCase(type)) {
|
||||
return new XiaomiPhone();
|
||||
} else if ("huawei".equalsIgnoreCase(type)) {
|
||||
return new HuaweiPhone();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Phone getPhone(Class<? extends Phone> phoneClass) {
|
||||
try {
|
||||
return (Phone) Class.forName(phoneClass.getName()).newInstance();
|
||||
} catch (InstantiationException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.heibaiying.creational.SimpleFactory;
|
||||
|
||||
|
||||
public class Test {
|
||||
public static void main(String[] args) {
|
||||
PhoneFactory phoneFactory = new PhoneFactory();
|
||||
phoneFactory.getPhone("xiaomi").call("123");
|
||||
phoneFactory.getPhone("huawei").call("321");
|
||||
phoneFactory.getPhone(XiaomiPhone.class).call("456");
|
||||
phoneFactory.getPhone(HuaweiPhone.class).call("654");
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.heibaiying.creational.SimpleFactory;
|
||||
|
||||
public class XiaomiPhone extends Phone {
|
||||
public void call(String phoneNum) {
|
||||
System.out.println("小米手机拨打电话:" + phoneNum);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user