1. // 雷锋类
    2. public class LeiFeng {
    3. public void Sweep(){
    4. System.out.println("扫地");
    5. }
    6. public void Wash(){
    7. System.out.println("洗衣");
    8. }
    9. public void BuyRice(){
    10. System.out.println("买米");
    11. }
    12. }
    13. // 学雷锋的大学生
    14. public class Undergraduate extends LeiFeng {
    15. }
    16. // 学雷锋的社区志愿者
    17. public class Volunteer extends LeiFeng {
    18. }
    19. // 雷锋工厂
    20. interface IFactory {
    21. LeiFeng createLeiFeng();
    22. }
    23. // 学雷锋的大学生工厂
    24. public class UndergraduateFactory implements IFactory{
    25. @Override
    26. public LeiFeng createLeiFeng() {
    27. return new Undergraduate();
    28. }
    29. }
    30. // 学雷锋的志愿者工厂
    31. public class VolunteerFactory implements IFactory{
    32. @Override
    33. public LeiFeng createLeiFeng() {
    34. return new Volunteer();
    35. }
    36. }
    37. // 通过反射来创建学生实例
    38. public class UnderReflection {
    39. private static final String FactoryName = "UndergraduateFactory";
    40. public static LeiFeng CreateUnder() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    41. UndergraduateFactory newInstance =(UndergraduateFactory)Class.forName("com.design.five.factory.mehtod.leifeng.factorymethod."+FactoryName).newInstance();
    42. return newInstance.createLeiFeng();
    43. }
    44. }
    45. // 通过反射获取志愿者实例
    46. public class VolunteerReflection {
    47. private static final String FactoryName = "VolunteerFactory";
    48. public static LeiFeng CreateVolunteer() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
    49. VolunteerReflection newInstance = (VolunteerReflection) Class.forName("com.design.five.factory.mehtod.leifeng.factorymethod."+FactoryName).newInstance();
    50. return newInstance.CreateVolunteer();
    51. }
    52. }
    53. public class Test {
    54. public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    55. // 使用工厂方法
    56. IFactory undergraduateFactory = new UndergraduateFactory();
    57. LeiFeng createLeiFeng = undergraduateFactory.createLeiFeng();
    58. createLeiFeng.BuyRice();
    59. IFactory volunteerFactory = new VolunteerFactory();
    60. LeiFeng createLeiFeng1 = volunteerFactory.createLeiFeng();
    61. createLeiFeng1.BuyRice();
    62. // 使用反射
    63. LeiFeng under = UnderReflection.CreateUnder();
    64. under.BuyRice();
    65. LeiFeng volunteer = VolunteerReflection.CreateVolunteer();
    66. volunteer.BuyRice();
    67. }
    68. }