接口模式:
基本接口定义:
package com.example.designpatten.decoratormode.interfacemode; public interface Gun { public void shoot(); public void aim(); public void load(); public void unLoad(); }
一个抽象类实现该接口并且持有该接口:
package com.example.designpatten.decoratormode.interfacemode; public abstract class GunBaseClass implements Gun { private Gun gun; public GunBaseClass(Gun gun) { this.gun = gun; } @Override public void shoot() { gun.shoot(); } @Override public void aim() { gun.aim(); } @Override public void load() { gun.load(); } @Override public void unLoad() { gun.unLoad(); } }
定义消音器功能类实现基础类
package com.example.designpatten.decoratormode.interfacemode; public class Sight extends GunBaseClass { public Sight(Gun gun) { super(gun); } @Override public void aim() { super.aim(); System.out.println("已加装瞄准镜"); } }
定义静音器类继承基础类:
package com.example.designpatten.decoratormode.interfacemode; public class Silencer extends GunBaseClass { public Silencer(Gun gun) { super(gun); } @Override public void shoot() { super.shoot(); System.out.println("已加装消音器,开枪声音小了"); } }
定义AK47枪支实现接口:
package com.example.designpatten.decoratormode.interfacemode; public class AK47 implements Gun { @Override public void shoot() { System.out.println("AK47 shoot!"); } @Override public void aim() { System.out.println("AK47 aim!"); } @Override public void load() { System.out.println("AK47 load!"); } @Override public void unLoad() { System.out.println("AK47 unLoad!"); } }
测试类测试:
package com.example.designpatten.decoratormode.interfacemode; import com.example.DemoApplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TestInterface { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); Gun gun = new Sight(new Silencer(new AK47())); gun.unLoad(); gun.load(); gun.aim(); gun.shoot(); } }
输出结果:
ps:继承模式待后续补充。