Factory Pattern Example In Java

 package demo;


public interface Student {


public String getCourse();


}



package demo;

public class PCCCSStudent implements Student {

@Override
public String getCourse() {
return "BCA";
}

}


package demo;

public class DYStudent implements Student {

@Override
public String getCourse() {
return "BCS";
}

}



package demo;

public class StudentFactory {

public Student getStudent(String student) {
Student std = null;
if (student.equals("PCCCS")) {
std = new PCCCSStudent();
} else if (student.equals("DY")) {
std = new DYStudent();
} else {
return std;
}
return std;
}

}



package demo;

public class TestFactory {
public static void main(String[] args) {

StudentFactory sfact = new StudentFactory();
Student s1 = sfact.getStudent("PCCCS");
Student s2 = sfact.getStudent("DY");
System.out.println("Course taken by first student "+s1.getCourse());
System.out.println("Course taken by second student "+s2.getCourse());
}
}

Comments

Popular posts from this blog

3 Lines of Code And You Can Download Your Favourite Youtube Video.

Leetcode Problem(Easy) Roman to Integer

Leetcode : (Find Minimum in Rotated Sorted Array)