提供一个创建对象实例的功能,而无需关心其具体实现,被创建的实例的类型可以是接口,抽象类,也可以是具体的类。
1.接口
package com.yl.design;
public interface Phone {
void display();
}
2.实现类1
package com.yl.design;
public class Huawei implements Phone {
@Override
public void display() {
System.out.println("Huawei...");
}
}
3.实现类2
package com.yl.design;
public class Apple implements Phone {
@Override
public void display() {
System.out.println("apple...");
}
}
4.工厂类
package com.yl.design;
public class SimpleFactory {
//私有化构造器,不给外部new
private SimpleFactory(){}
//定义一个静态的方法,用于生产对象
public static Phone CreatePhone(int flag) {
Phone phone = null;
if (flag == 1) {
phone = new Apple();
} else if (flag == 2) {
phone = new Huawei();
}
return phone;
}
}
5.测试
package com.yl.design;
public class test {
public static void main(String[] args) {
Phone phone = SimpleFactory.CreatePhone(2);
phone.display();
}
}
1.在原来代码的基础上,加多一个factory.properties文件
2.工厂(利用反射构造实例)
package com.yl.design;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Factory {
private Factory(){}
public static Phone createPhone() {
Properties properties = new Properties();
InputStream in = null;
try {
in = Factory.class.getResourceAsStream("factory.properties");
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//利用反射创建实例
Phone phone = null;
try {
phone = (Phone)Class.forName(properties.getProperty("AppleClass")).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return phone;
}
}
3.测试
package com.yl.design;
public class test {
public static void main(String[] args) {
// Phone phone = SimpleFactory.CreatePhone(2);
// phone.display();
Phone phone = Factory.createPhone();
phone.display();
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_41359273/article/details/123279406
内容来源于网络,如有侵权,请联系作者删除!