zoukankan      html  css  js  c++  java
  • 抽象类应用--模板设计(理解)

    简述

    例如,现在有三类事物:
    机器人:充电,工作;
    人:吃饭、工作、睡觉
    猪:吃饭、睡觉
    要求可以实现以上的操作控制,即可以控制人、机器人、猪的操作行为(吃、睡觉、工作)

    定义一个行为类

    abstract class Action {
    	public static final int EAT = 1;
    	public static final int SLEEP = 5;
    	public static final int WORK = 7;
    	public void command(int flag){
    		// switch只支持数值判断,if支持条件判断
    		switch(flag){
    			case EAT:
    				this.eat();
    				break;
    			case SLEEP:
    				this.sleep();
    				break;
    			case WORK:
    				this.work();
    				break;
    			case EAT + SLEEP:
    				this.eat();
    				this.sleep();
    				break;
    		}
    	}
    	// 因为现在不确定子类的实现是什么样的
    	public abstract void eat();
    	public abstract void sleep();
    	public abstract void work();
    
    }
    

    定义机器人的类

    class Rebot extends Action{
    	public void eat(){
    		System.out.println("机器人下在补充能量");
    	}
    	public void work(){
    		System.out.println("机器人下在努力工作");
    	}
    	public void sleep() {}
    }
    

    定义人这个类

    class Human extends Action{
    	public void eat(){
    		System.out.println("人正在吃饭");
    	}
    	public void sleep(){
    		System.out.println("人正在睡觉");
    	}
    	public void work(){
    		System.out.println("人正在为梦想努力奋斗");
    	}
    }
    

    定义猪这个类

    class Pig extends Action{
    	public void eat(){
    		System.out.println("猪正在吃饲料");
    	}
    	public void sleep(){
    		System.out.println("猪下在长肉");
    	}
    	public void work(){}
    }
    

    调用测试

    public class testDemo{
    	public static void main(String args[]){
    		func(new Rebot());
    		func(new Human());
    		func(new Pig());
    	}
    	public static void func(Action act){
    		act.command(Action.EAT);	
    		act.command(Action.SLEEP);	
    		act.command(Action.WORK);	
    	}
    }
    

    总结

    1.如果真的要使用类继承,那么就使用抽象类(20%的情况)
    2.抽象类强制规定了子类必须要做的事情,而且可以与抽象类的普通方法想配合
    3.不管抽象类如何努力都有一个天生最大的问题:单继承局限

  • 相关阅读:
    (转)Linux 信号说明列表
    linux下socket函数之listen的参数backlog
    (转)auto_ptr与shared_ptr
    (转)关于两次fork
    收集外链
    (转+整理)Linux下Makefile的automake生成全攻略
    LINUX socket编程(转载)errno.h
    (转) socket编程——sockaddr_in结构体操作
    k Nearest Neighbor Search by CUDA
    CUDA Anisotropic Diffusion on a 2D Image
  • 原文地址:https://www.cnblogs.com/anyux/p/11962656.html
Copyright © 2011-2022 走看看