简单工厂模式

This commit is contained in:
luoxiang
2019-11-30 18:24:41 +08:00
parent 538f89ebc9
commit b42b937cdf
6 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package com.heibaiying.creational.SimpleFactory;
public class HuaweiPhone extends Phone {
public void call(String phoneNum) {
System.out.println("华为手机拨打电话:" + phoneNum);
}
}

View File

@ -0,0 +1,8 @@
package com.heibaiying.creational.SimpleFactory;
/**
* 手机
*/
public abstract class Phone {
public abstract void call(String phoneNum);
}

View File

@ -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;
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,7 @@
package com.heibaiying.creational.SimpleFactory;
public class XiaomiPhone extends Phone {
public void call(String phoneNum) {
System.out.println("小米手机拨打电话:" + phoneNum);
}
}