1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package FactoryClass;
import java.lang.reflect.Constructor;
interface VolunteerServiceRef { void provideHelpRef(); }
class HomeCleaningRef implements VolunteerServiceRef { @Override public void provideHelpRef() { System.out.println("提供家庭清洁服务"); } }
class CompanionshipRef implements VolunteerServiceRef { @Override public void provideHelpRef() { System.out.println("提供陪伴聊天服务"); } }
interface VolunteerOrganizationRef { VolunteerServiceRef createVolunteerServiceRef() throws Exception; }
class ReflectiveVolunteerOrganization implements VolunteerOrganizationRef { private Class<? extends VolunteerServiceRef> serviceClass;
public ReflectiveVolunteerOrganization(Class<? extends VolunteerServiceRef> serviceClass) { this.serviceClass = serviceClass; }
@Override public VolunteerServiceRef createVolunteerServiceRef() throws Exception { Constructor<? extends VolunteerServiceRef> constructor = serviceClass.getDeclaredConstructor(); return constructor.newInstance(); } }
public class ElderlySupportReflection { public static void main(String[] args) { try { VolunteerOrganizationRef homeHelp = new ReflectiveVolunteerOrganization(HomeCleaningRef.class); VolunteerServiceRef homeCleaningService = homeHelp.createVolunteerServiceRef(); homeCleaningService.provideHelpRef();
VolunteerOrganizationRef socialCare = new ReflectiveVolunteerOrganization(CompanionshipRef.class); VolunteerServiceRef companionshipService = socialCare.createVolunteerServiceRef(); companionshipService.provideHelpRef(); } catch (Exception e) { e.printStackTrace(); } } }
|