zoukankan      html  css  js  c++  java
  • 桥接模式——Java实现

    问题描述:

    用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。

    类图:

    Java源代码:

    //Road.java
    package shiyan9;
    
    public abstract class Road {
        protected Vehicle vehicle;
        public void setVehicle(Vehicle ve) {
            this.vehicle=ve;
        }
        public abstract void drive();
    }
    //Shuini.java
    package shiyan9;
    
    public class Shuini extends Road{
        public void drive() {
            vehicle.run();
            System.out.println("行驶在水泥路");
        }
    }
    //Liqing.java
    package shiyan9;
    
    public class liqing extends Road{
        public void drive() {
            vehicle.run();
            System.out.println("行驶在沥青路");
        }
    }
    //Vehicle.java
    package shiyan9;
    
    public interface Vehicle {
        public void run();
    }
    //Bus.java
    package shiyan9;
    
    public class Bus implements Vehicle{
        @Override
        public void run() {
            System.out.print("Bus");    
        }
    }
    //Car.java
    package shiyan9;
    
    public class Car implements Vehicle{
        @Override
        public void run() {
            System.out.print("Car");    
        }
    }
    //Main.java
    package shiyan9;
    
    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
            Vehicle vehicle = null;
            Road road = null;
            System.out.println("请选择:1、Car/水泥路  2、Car/沥青路  3、Bus/水泥路  4、Bus/沥青路");
            Scanner input=new Scanner(System.in);
            int i=input.nextInt();
            if(i==1) {
                vehicle=(Vehicle)new Car();
                road=(Road)new Shuini();
            }else if(i==2) {
                vehicle=(Vehicle)new Car();
                road=(Road)new liqing();
            }else if(i==3){
                vehicle=(Vehicle)new Bus();
                road=(Road)new Shuini();
            }else if(i==4) {
                vehicle=(Vehicle)new Bus();
                road=(Road)new liqing();
            }else {
                System.out.println("输入无效!");
            }
            road.setVehicle(vehicle);
            road.drive();
        }
    }

    运行结果:

     

     

     

  • 相关阅读:
    Admin添加字段
    django admin基础
    user_admin
    admin 模块功能
    todolist项目
    Django进阶项目
    Django进阶
    bolg项目
    EL&jstl
    模拟用户登录,内含验证码验证和request等操作
  • 原文地址:https://www.cnblogs.com/znjy/p/14138176.html
Copyright © 2011-2022 走看看