Product.java代码如下:
package com.designPattern.bridge;
/**
*
* @author yangjianzhou
* 这是整个集团公司的产品类
*/
public abstract class Product {
public abstract void beProducted();
public abstract void beSelled();
}
House.java代码如下:
package com.designPattern.bridge;
public class House extends Product{
@Override
public void beProducted() {
System.out.println("生产出的房子是这样的!");
}
@Override
public void beSelled() {
System.out.println("生产出的房子卖出去了!");
}
}
Clothes.java代码如下:
package com.designPattern.bridge;
public class Clothes extends Product{
@Override
public void beProducted() {
System.out.println("生产出的衣服是这样的!");
}
@Override
public void beSelled() {
System.out.println("衣服被卖出去了!");
}
}
IPod.java代码如下:
package com.designPattern.bridge;
public class IPod extends Product{
@Override
public void beProducted() {
System.out.println("生产出的IPod是这样的!");
}
@Override
public void beSelled() {
System.out.println("IPod被卖出去了!");
}
}
Corp.java 代码如下:
package com.designPattern.bridge;
public abstract class Corp {
/*
* 这就是桥梁
*/
private Product product;
/**
* 这个构造函数的目的就是让子类必须重写自己的有参构造函数,把产品类传进来
* @param product
*/
public Corp(Product product){
this.product = product;
}
public void makeMoney(){
this.product.beProducted();
this.product.beSelled();
}
}
HouseCorp.java代码如下:
package com.designPattern.bridge;
public class HouseCorp extends Corp{
public HouseCorp(House house) {
super(house);
}
@Override
public void makeMoney() {
super.makeMoney();
System.out.println("房地产公司赚大钱了!");
}
}
ShanZhaiCorp.java代码如下:
package com.designPattern.bridge;
public class ShanZhaiCorp extends Corp{
public ShanZhaiCorp(Product product) {
super(product);
}
@Override
public void makeMoney() {
super.makeMoney();
System.out.println("我赚钱了!");
}
}
Client.java代码如下:
package com.designPattern.bridge;
public class Client {
public static void main(String[] args) {
House house = new House();
System.out.println("================房地产公司是这样运作的=============");
HouseCorp houseCorp = new HouseCorp(house);
houseCorp.makeMoney();
System.out.println("==================山寨公司是这样运行的==============");
ShanZhaiCorp shanZhaiCorp = new ShanZhaiCorp(new IPod());
shanZhaiCorp.makeMoney();
System.out.println("==================山寨公司是这样运行的==============");
shanZhaiCorp = new ShanZhaiCorp(new Clothes());
shanZhaiCorp.makeMoney();
}
}
运行效果如下:
================房地产公司是这样运作的=============
生产出的房子是这样的!
生产出的房子卖出去了!
房地产公司赚大钱了!
==================山寨公司是这样运行的==============
生产出的IPod是这样的!
IPod被卖出去了!
我赚钱了!
==================山寨公司是这样运行的==============
生产出的衣服是这样的!
衣服被卖出去了!
我赚钱了!