JAVA 设计模式 工厂模式

package com.data.entity;

import java.util.Objects;

public class student {
    public String name;
    public int age;
    public double score;
    public student(){}
    public student(String name,int age,double score){
        this.name=name;
        this.age=age;
        this.score=score;
    }

    public int getScore(){
        return this.age;
    }

//    @Override
//    public String toString() {
//        return "student{" +
//                "name='" + name + '\'' +
//                ", age=" + age +
//                ", score=" + score +
//                '}';
//    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof student student)) return false;
        return age == student.age && Double.compare(score, student.score) == 0 && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, score);
    }
}
在当前项目下新建`xxx.properties`配置文件

classNames.properties

StudentClassName=com.data.entity.student
package com.data.entity;

import java.io.FileInputStream;
import java.util.Properties;

public class MyFactory {
    /**
     * 获取学生类的实例对象
     * @return 学生对象实例
     */
    public static student newStudent(){
        student stu=null;
        try (
                //创建字节输入流
                FileInputStream fis=new FileInputStream("classNames.properties")
        ) {
            //将配置文件中的内容读取存放至Properties集合
            Properties p = new Properties();
            p.load(fis);
            //获取学生类的全限定名
            String studentClassName = p.getProperty("StudentClassName");
            //通过Class.forName获取类对象
            Class c = Class.forName(studentClassName);
            //通过类对象构建学生实例
            stu = (student) c.newInstance();
        } catch (Exception e) {
            System.out.println("未知异常");
            e.printStackTrace();
        }

        return stu;
    }
}
import com.data.entity.ClassA;
import com.data.entity.MyFactory;
import com.data.entity.MyList;
import com.data.entity.student;

import java.lang.reflect.Constructor;

public class text8 {
    public static void main(String[] args)throws Exception {
//利用工厂获取学生实例对象
        student s = MyFactory.newStudent();
        student s2 = MyFactory.newStudent();
        System.out.println(s);
        System.out.println(s2);
    }
}

你可能感兴趣的:(java,设计模式,python)