模版方法模式

1. 自定义classload    重载了findclass 方法 而没有覆盖loadclass 

 

 

 

	   protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
    {
	// First, check if the class has already been loaded
	Class c = findLoadedClass(name);
	if (c == null) {
	    try {
		if (parent != null) {
		    c = parent.loadClass(name, false);
		} else {
		    c = findBootstrapClass0(name);
		}
	    } catch (ClassNotFoundException e) {
	        // If still not found, then invoke findClass in order
	        // to find the class.
	        c = findClass(name);
	    }
	}
	if (resolve) {
	    resolveClass(c);
	}
	return c;
    }

loadclass 父类调用了findclass();  loadclass 里面有了业务步骤 最后调用findclass .自定义后的类加载器 需要实现findclass 就OK 其他交给父类完成

 

public abstract class HummerModel {
 
 
public abstract void start();
 

 
public abstract void stop();
 

 
public abstract void alarm();
 

 
public abstract void engineBoom();

 /*模版*/
public void run(){ 
this.start(); 
this.engineBoom(); 
 
this.alarm(); 
 
this.stop();
 
}
 
}



public class HummerH1Model extends HummerModel {
 
//H1型号的悍马车鸣笛
 
public void alarm() {
 
System.out.println("悍马H1鸣笛...");
 
}
 
//引擎轰鸣声
 
public void engineBoom() {
 
System.out.println("悍马H1引擎声音是这样在...");
 
}
 
//汽车发动
 
public void start() {
 
System.out.println("悍马H1发动...");
 
}
 
//停车
 
public void stop() {
 
System.out.println("悍马H1停车...");
 
}

此方法写在父抽象类中
//public void run(){
 
//先发动汽车
 
//this.start(); 
 
//引擎开始轰鸣
// 
//this.engineBoom(); 
 
//然后就开始跑了,跑的过程中遇到一条狗挡路,就按喇叭
 
//this.alarm(); 
 
//到达目的地就停车
 
//this.stop();
 
//}



}

main(){

HummerModel h1 = new HummerH1Model();
 
//H1模型演示
 
h1.run();

HummerModel h1 = ne2 HummerH2Model();

h2.run();

}
 

 

 

 

 

 

你可能感兴趣的:(方法)