1、不加配置类方式
package com.zhz.test.gof.factory;
/**
* 默认方法就是public abstract=>不加配置文件的
* @author zhouhengzhe
* @Description: 水果类
* @date 2021/7/15上午10:44
*/
public interface Fruit {
void eat();
}
class Apple implements Fruit{
@Override
public void eat() {
System.out.println("吃苹果(Apple)");
}
}
class Orange implements Fruit{
@Override
public void eat() {
System.out.println("吃橘子(Orange)");
}
}
class Factory{
public static Fruit getInstance(String className){
Fruit fruit=null;
try {
fruit = (Fruit) Class.forName(className).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return fruit;
}
}
class Test{
public static void main(String[] args) {
Fruit fruit=Factory.getInstance("com.zhz.test.gof.factory.Apple");
if (fruit!=null){
fruit.eat();
}
}
}
2、加配置类方式(工厂方法+反射+配置类)
package com.zhz.test.gof.factory;
import java.io.*;
import java.util.Properties;
/**
* @author zhouhengzhe
* @Description: 加配置文件的
* @date 2021/7/15上午10:52
*/
public interface FruitByProperties {
void eat();
}
class AppleByProperties implements FruitByProperties{
@Override
public void eat() {
System.out.println("吃苹果(Apple)");
}
}
class OrangeByProperties implements FruitByProperties{
@Override
public void eat() {
System.out.println("吃橘子(Orange)");
}
}
//增加一个初始化配置的类,集成spring的话可以省略这一步
class Init{
public static Properties getPro() throws IOException {
Properties properties=new Properties();
File file = new File("fruit.properties");
if (file.exists()){
properties.load(new FileInputStream(file));
}else {
properties.setProperty("apple","com.zhz.test.gof.factory.AppleByProperties");
properties.setProperty("orange","com.zhz.test.gof.factory.OrangeByProperties");
//加注释
properties.store(new FileOutputStream(file),"FRUIT CLASS");
}
return properties;
}
}
class FactoryByProperties{
public static FruitByProperties getInstance(String className){
FruitByProperties fruit=null;
try {
fruit = (FruitByProperties) Class.forName(className).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return fruit;
}
}
class TestByProperties {
public static void main(String[] args) throws IOException {
Properties properties=Init.getPro();
FruitByProperties fruit = FactoryByProperties.getInstance(properties.getProperty("apple"));
if (fruit != null) {
fruit.eat();
}
}
}
配置类:fruit.properties
apple=com.zhz.test.gof.factory.AppleByProperties
orange=com.zhz.test.gof.factory.OrangeByProperties
下面是本人的公众号:(有兴趣可以扫一下,文章会同步过去)
我是小白弟弟,一个在互联网行业的小白,立志成为一名架构师
https://blog.csdn.net/zhouhengzhe?t=1