简单工厂模式

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,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.heibaiying</groupId>
<artifactId>design-pattern</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

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