Reflection in factory design patterns in Java or C#

前端 未结 2 2013
日久生厌
日久生厌 2021-01-25 21:13

I came across a term called reflection. It is a feature commonly used in factory design patterns. I had a hard time understanding the concept because I’m still learning how to p

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 21:43

    Java version for this question

    Code:

    public class TestReflectionFactoryDesign {
    
        public static void main(String[] args) throws Exception {
            Person student = PersonFactory.getPersonWithFullQualifiedClassName("com.test.reflectionFactoryDesign.Student");
            student.say();
            Person teacher = PersonFactory.getPersonWithClass(Teacher.class);
            teacher.say();
            Person student2 = PersonFactory.getPersonWithName("student");
            student2.say();
        }
    }
    
    class Student implements Person {
        @Override
        public void say() {
            System.out.println("I am a student");
        }
    }
    
    class Teacher implements Person {
        @Override
        public void say() {
            System.out.println("I am a teacher");
        }
    }
    
    interface Person {
        void say();
    }
    
    class PersonFactory {
        // reflection, by full qualified class name
        public static Person getPersonWithFullQualifiedClassName(String personType) throws Exception {
            Class personClass = Class.forName(personType);
            return getPersonWithClass(personClass);
        }
    
        // reflection, by passing class object
        public static Person getPersonWithClass(Class personClass) throws Exception {
            return (Person) personClass.newInstance();
        }
    
        // no reflection, the ordinary way
        public static Person getPersonWithName(String personType) {
            if (personType.equalsIgnoreCase("STUDENT")) {
                return new Student();
            } else if (personType.equalsIgnoreCase("TEACHER")) {
                return new Teacher();
            }
    
            return null;
        }
    }
    

    Output:

    I am a student
    I am a teacher
    I am a student
    

提交回复
热议问题