/**
* 适配器模式
*/
public class AdapterCase01 {
public static void main(String[] args) {
new Phone().charging(new ClassVoltageAdapter());
}
}
/**
* 被适配的类
*/
class Voltage220V {
public int output220V() {
int src = 220;
System.out.println("电压" + src + "V");
return src;
}
}
/**
* 适配接口
*/
interface IVoltage5V {
int output5V();
}
/**
* 手机
*/
class Phone {
void charging(IVoltage5V voltage5V) {
int output = voltage5V.output5V();
if (output == 5) {
System.out.println("电压为5V,可以充电");
} else if (output > 5) {
System.out.println("电压大于5V,不可以充电");
}
}
}
/**
* 类适配器
*/
class ClassVoltageAdapter extends Voltage220V implements IVoltage5V {
@Override
public int output5V() {
System.out.println("----类适配器----");
int srcV = output220V();
int dstV = srcV / 44;
return dstV;
}
}
/**
* 对象适配器
*/
class ObjectVoltageAdapter implements IVoltage5V {
private Voltage220V voltage220V;
ObjectVoltageAdapter(Voltage220V voltage220V) {
this.voltage220V = voltage220V;
}
@Override
public int output5V() {
System.out.println("----对象适配器----");
int srcV = voltage220V.output220V();
int dstV = srcV / 44;
return dstV;
}
}
public class AdapterCase02 {
public static void main(String[] args) {
AbstractAadpter adpter = new AbstractAadpter() {
@Override
public void m1() {
System.out.println("m1");
}
};
adpter.m1();
}
}
interface InterfaceA {
void m1();
void m2();
void m3();
void m4();
}
abstract class AbstractAadpter implements InterfaceA {
@Override public void m1() {}
@Override public void m2() {}
@Override public void m3() {}
@Override public void m4() {}
}
// 处理器
public interface Handler {
void doHandle();
}
class SimpleHandler implements Handler {
@Override
public void doHandle() {
System.out.println("SimpleHandler.doHandle() ...");
}
}
class HttpHandler implements Handler {
@Override
public void doHandle() {
System.out.println("HttpHandler.doHandle() ...");
}
}
class AnnotationHandler implements Handler {
@Override
public void doHandle() {
System.out.println("AnnotationHandler.doHandle() ...");
}
}
// 处理器适配器
public interface HandlerAdapter {
boolean support(Handler handler);
void handle(Handler handler);
}
class SimpleHandlerAdapter implements HandlerAdapter {
@Override
public boolean support(Handler handler) {
return handler instanceof SimpleHandler;
}
@Override
public void handle(Handler handler) {
handler.doHandle();
}
}
class HttpHandlerAdapter implements HandlerAdapter {
@Override
public boolean support(Handler handler) {
return handler instanceof HttpHandler;
}
@Override
public void handle(Handler handler) {
handler.doHandle();
}
}
class AnnotationHandlerAdapter implements HandlerAdapter {
@Override
public boolean support(Handler handler) {
return handler instanceof AnnotationHandler;
}
@Override
public void handle(Handler handler) {
handler.doHandle();
}
}
// 分派
public class DispatchServlet {
private static List<HandlerAdapter> handlerAdapters = new ArrayList<>();
public DispatchServlet() {
handlerAdapters.add(new SimpleHandlerAdapter());
handlerAdapters.add(new HttpHandlerAdapter());
handlerAdapters.add(new AnnotationHandlerAdapter());
}
public void doDispatch() {
HttpHandler handler = new HttpHandler();
HandlerAdapter adapter = getHandler(handler);
if (adapter != null) {
adapter.handle(handler);
}
}
private HandlerAdapter getHandler(Handler handler) {
for (HandlerAdapter adapter : handlerAdapters) {
if (adapter.support(handler)) {
return adapter;
}
}
return null;
}
public static void main(String[] args) {
new DispatchServlet().doDispatch();
}
}
现在对不同手机类型的不同品牌实现操作编程(比如:开机、关机、上网,打电话等),如图:
* 抽象类(Abstraction):维护了Implementor,及其实现子类,两者是聚合关系,Abstraction充当桥接类
* RefinedAbstraction:是Abstraction抽象类的实现子类
* Implementor:是行为实现类的接口
* ConcreteImplementorA、ConcreteImplementorB:是行为的具体实现类
public class BridgeCase01 {
public static void main(String[] args) {
Phone foldedXiaoMi = new FoldedPhone(new XiaoMi());
foldedXiaoMi.open();
foldedXiaoMi.close();
foldedXiaoMi.call();
System.out.println("===============");
Phone foldedViVo = new FoldedPhone(new ViVo());
foldedViVo.open();
foldedViVo.close();
foldedViVo.call();
}
}
/**
* 手机品牌:Implementor行为实现类的接口
*/
interface Brand {
void open();
void close();
void call();
}
/**
* 小米手机:行为的具体实现类
*/
class XiaoMi implements Brand {
@Override
public void open() {
System.out.println("小米手机开机");
}
@Override
public void close() {
System.out.println("小米手机关机");
}
@Override
public void call() {
System.out.println("小米手机打电话");
}
}
/**
* ViVo手机:行为的具体实现类
*/
class ViVo implements Brand {
@Override
public void open() {
System.out.println("ViVo手机开机");
}
@Override
public void close() {
System.out.println("ViVo手机关机");
}
@Override
public void call() {
System.out.println("ViVo手机打电话");
}
}
/**
* 手机样式:抽象类(Abstraction)
*/
abstract class Phone {
/**
* 组合进 品牌
*/
private Brand brand;
Phone(Brand brand) {
this.brand = brand;
}
protected void open() {
this.brand.open();
}
protected void close() {
this.brand.close();
}
protected void call() {
this.brand.call();
}
}
/**
* 手机样式具体的实现子类
*/
class FoldedPhone extends Phone {
private static final String STYLE = "折叠样式";
FoldedPhone(Brand brand) {
super(brand);
}
@Override
public void open() {
System.out.print(STYLE);
super.open();
}
@Override
public void close() {
System.out.print(STYLE);
super.close();
}
@Override
public void call() {
System.out.print(STYLE);
super.call();
}
}
//折叠样式小米手机开机
//折叠样式小米手机关机
//折叠样式小米手机打电话
//===============
//折叠样式ViVo手机开机
//折叠样式ViVo手机关机
//折叠样式ViVo手机打电话
class UpRightPhone extends Phone {
private static final String STYLE = "直立样式";
UpRightPhone(Brand brand) {
super(brand);
}
@Override
public void open() {
System.out.print(STYLE);
super.open();
}
@Override
public void close() {
System.out.print(STYLE);
super.close();
}
@Override
public void call() {
System.out.print(STYLE);
super.call();
}
}
public class BridgeCase01 {
public static void main(String[] args) {
Phone upRightXiaomi = new UpRightPhone(new XiaoMi());
upRightXiaomi.open();
upRightXiaomi.close();
upRightXiaomi.call();
}
}
//直立样式小米手机开机
//直立样式小米手机关机
//直立样式小米手机打电话
public class DecoratorCase {
public static void main(String[] args) {
// 2份巧克力+一份牛奶的 LongBlack
// 1、点一份 LongBlack
Drink order = new LongBlack();
System.out.println("费用1 = " + order.getCost() + ",描述 = " + order.getDesc());
// 2、order加入一份牛奶
order = new Milk(order);
System.out.println("费用2 = " + order.getCost() + ",描述 = " + order.getDesc());
// 3、order加入一份巧克力
order = new Chocolate(order);
System.out.println("费用3 = " + order.getCost() + ",描述 = " + order.getDesc());
// 4、order再加入一份巧克力
order = new Chocolate(order);
System.out.println("费用4 = " + order.getCost() + ",描述 = " + order.getDesc());
}
}
/**
* 被装饰者:Component
*/
@Data
abstract class Drink {
private String desc;
private float price;
abstract float getCost();
}
class Coffee extends Drink {
@Override
float getCost() {
return super.getPrice();
}
}
/**
* 具体的被装饰者
*/
class Espresso extends Coffee {
Espresso() {
setDesc("意大利咖啡");
setPrice(6.0f);
}
}
class LongBlack extends Coffee {
LongBlack() {
setDesc("LongBlack");
setPrice(5.0f);
}
}
class ShortBlack extends Coffee {
ShortBlack() {
setDesc("ShortBlack");
setPrice(4.0f);
}
}
/**
* 装饰者
*/
class Decorator extends Drink {
private Drink drink;
Decorator(Drink drink) {
this.drink = drink;
}
@Override
float getCost() {
return super.getPrice() + drink.getCost();
}
@Override
public String getDesc() {
// drink.getDesc() 是被装饰者的信息
return super.getDesc() + " " + super.getPrice() + " && " + drink.getDesc();
}
}
/**
* 具体的装饰者:调味品
*/
class Chocolate extends Decorator {
Chocolate(Drink drink) {
super(drink);
setDesc(" 巧克力 ");
// 调味品的价格
setPrice(3.0f);
}
}
class Milk extends Decorator {
Milk(Drink drink) {
super(drink);
setDesc(" 牛奶 ");
setPrice(2.0f);
}
}
class Soy extends Decorator {
Soy(Drink drink) {
super(drink);
setDesc(" 豆浆 ");
setPrice(1.5f);
}
}
public abstract class InputStream implements Closeable{} // 是一个抽象类,即Component
public class FilterInputStream extends InputStream {// 是一个装饰者类Decorator
protected volatile InputStream in; // 被装饰的对象
}
public class DataInputStream extends FilterInputStream implements DataInput {} // 是 FilterInputStream 子类,也继承了被装饰的对象 InputStream
* Component : 这是组合中对象声明接口,在适当情况下,实现所有类共有的接口默认行为,用于访问和管理Component 子部件, Component 可以是抽象类或者接口
* Leaf : 在组合中表示叶子节点,叶子节点没有子节点
* Composite : 非叶子节点, 用于存储子部件, 在 Component 接口中实现 子部件的相关操作,比如增加(add),删除
public class CompositeCase {
public static void main(String[] args) {
// 从大到小创建对象
University university = new University("清华大学");
College college1 = new College("计算机学院");
College college2 = new College("信息工程学院");
college1.add(new Department("软件工程"));
college1.add(new Department("网络安全"));
college1.add(new Department("计算机科学与技术"));
college2.add(new Department("通信工程"));
college2.add(new Department("信息工程"));
// college1.print();
university.add(college1);
university.add(college2);
university.print();
}
}
@Data
abstract class OrgComponent {
private String name;
OrgComponent(String name){
this.name = name;
}
protected void add(OrgComponent component) {
// 默认实现
throw new UnsupportedOperationException();
}
protected void remove(OrgComponent component) {
// 默认实现
throw new UnsupportedOperationException();
}
protected void get(int index) {
// 默认实现
throw new UnsupportedOperationException();
}
abstract void print();
}
class University extends OrgComponent {
List<OrgComponent> components = new ArrayList<>();
University(String name) {
super(name);
}
@Override
public void add(OrgComponent component) {
components.add(component);
}
@Override
public void remove(OrgComponent component) {
components.remove(component);
}
@Override
public void get(int index) {
components.get(index);
}
@Override
public void print() {
System.out.println("--------" + getName() +"--------");
if (components.size() > 0) {
for (OrgComponent component : components) {
component.print();
}
}
}
}
class College extends OrgComponent {
List<OrgComponent> components = new ArrayList<>();
College(String name) {
super(name);
}
@Override
public void add(OrgComponent component) {
// 实际业务中,add方法不一定完全一样
components.add(component);
}
@Override
public void remove(OrgComponent component) {
components.remove(component);
}
@Override
public void get(int index) {
components.get(index);
}
@Override
public void print() {
System.out.println("--------" + getName() +"--------");
if (components.size() > 0) {
for (OrgComponent component : components) {
component.print();
}
}
}
}
/**
* 叶子结点
*/
class Department extends OrgComponent {
Department(String name) {
super(name);
}
@Override
public void print() {
System.out.println(getName());
}
}
public class JDKComposite {
public static void main(String[] args) {
/*
Map 就是一个抽象的构建(类似组合模式里面的Component)
HashMap是一个中间的构建(Composite),实现/继承了相关方法:put、putAll
Node 是 HasMap 的静态内部类,类似于 Leaf 叶子结点,没有 put、putAll 方法
*/
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(0, "西游记");
Map<Integer, String> map = new HashMap<>();
map.put(1, "水浒传");
map.put(2, "红楼梦");
hashMap.putAll(map);
System.out.println(hashMap);
}
}
• 直接用遥控器:统筹各设备开关 • 开爆米花机
• 放下屏幕
• 开投影仪
• 开音响
• 开DVD,选dvd
• 去拿爆米花
• 调暗灯光
• 播放
• 观影结束后,关闭各种设备
public class FacadeCase {
public static void main(String[] args) {
// 如果直接调用,很不方便
HomeTheaterFacade facade = new HomeTheaterFacade();
facade.ready();
facade.play();
facade.end();
}
}
class DVDPlayer {
private DVDPlayer() {}
private static DVDPlayer INSTANCE = new DVDPlayer();
public static DVDPlayer getInstance() {
return INSTANCE;
}
public void on() {
System.out.println("DVD on");
}
public void off() {
System.out.println("DVD off");
}
public void play() {
System.out.println("DVD playing");
}
public void pause() {
System.out.println("DVD paused");
}
}
class Popcorn {
private Popcorn() {}
private static Popcorn INSTANCE = new Popcorn();
public static Popcorn getInstance() {
return INSTANCE;
}
public void on() {
System.out.println("Popcorn on");
}
public void off() {
System.out.println("Popcorn off");
}
public void pop() {
System.out.println("Popcorn popping");
}
}
class Projector {
private Projector() {}
private static Projector INSTANCE = new Projector();
public static Projector getInstance() {
return INSTANCE;
}
public void on() {
System.out.println("Projector on");
}
public void off() {
System.out.println("Projector off");
}
public void focus() {
System.out.println("Projector focus");
}
}
class Screen {
private Screen() {}
private static Screen INSTANCE = new Screen();
public static Screen getInstance() {
return INSTANCE;
}
public void up() {
System.out.println("Screen up");
}
public void down() {
System.out.println("Screen down");
}
}
class Stereo {
private Stereo() {}
private static Stereo INSTANCE = new Stereo();
public static Stereo getInstance() {
return INSTANCE;
}
public void on() {
System.out.println("Stereo on");
}
public void off() {
System.out.println("Stereo off");
}
public void up() {
System.out.println("Stereo up");
}
public void down() {
System.out.println("Stereo down");
}
}
class TheaterLight {
private TheaterLight() {}
private static TheaterLight INSTANCE = new TheaterLight();
public static TheaterLight getInstance() {
return INSTANCE;
}
public void on() {
System.out.println("TheaterLight on");
}
public void off() {
System.out.println("TheaterLight off");
}
public void dim() {
System.out.println("TheaterLight dim");
}
public void bright() {
System.out.println("TheaterLight bright");
}
}
class HomeTheaterFacade {
/**
* 定义各个子系统的对象
*/
private DVDPlayer dvdPlayer;
private Popcorn popcorn;
private Projector projector;
private Screen screen;
private Stereo stereo;
private TheaterLight theaterLight;
public HomeTheaterFacade() {
this.dvdPlayer = DVDPlayer.getInstance();
this.popcorn = Popcorn.getInstance();
this.projector = Projector.getInstance();
this.screen = Screen.getInstance();
this.stereo = Stereo.getInstance();
this.theaterLight = TheaterLight.getInstance();
}
public void ready(){
popcorn.on();
popcorn.pop();
screen.down();
projector.on();
stereo.on();
dvdPlayer.on();
theaterLight.dim();
}
public void play() {
dvdPlayer.play();
}
public void pause() {
dvdPlayer.pause();
}
public void end() {
popcorn.off();
screen.up();
projector.off();
stereo.off();
dvdPlayer.off();
theaterLight.off();
}
}
比如围棋、五子棋、跳棋,它们都有大量的棋子对象,围棋和五子棋只有黑白两色,跳棋颜色多一点,所以棋子颜色就是棋子的内部状态;而各个棋子之间的差别就是位置的不同,当我们落子后,落子颜色是定的,但位置是变化的,所以棋子坐标就是棋子的外部状态。
public class FlyweightCase {
public static void main(String[] args) {
WebSiteFactory factory = new WebSiteFactory();
WebSite webSite1 = factory.getWebSite("新闻");
webSite1.use(new User("张三"));
WebSite webSite2 = factory.getWebSite("博客");
webSite2.use(new User("李四"));
WebSite webSite3 = factory.getWebSite("博客");
webSite3.use(new User("王五"));
System.out.println("网站的分类共 " + factory.getWebSiteCount() + " 个");
}
}
abstract class WebSite {
abstract void use(User user);
}
class ConcreteWebSite extends WebSite {
/**
* 网站类型:内部状态
*/
private String type;
ConcreteWebSite(String type) {
this.type = type;
}
@Override
public void use(User user) {
System.out.println("网站的发布形式:" + type + "," + user.getName() + "在使用中...");
}
}
class WebSiteFactory {
private Map<String, ConcreteWebSite> pool = new HashMap<>();
public WebSite getWebSite(String type) {
if (!pool.containsKey(type)) {
pool.put(type, new ConcreteWebSite(type));
}
return pool.get(type);
}
public int getWebSiteCount() {
return pool.size();
}
}
/**
* 外部状态
*/
@Data
@AllArgsConstructor
class User {
private String name;
}
//网站的发布形式:新闻,张三在使用中...
//网站的发布形式:博客,李四在使用中...
//网站的发布形式:博客,王五在使用中...
//网站的分类共 2 个
public class JDKFlyweight {
public static void main(String[] args) {
/*
如果 Integer.valueOf(x) x 在 -127~128 之间,就是使用的享元模式返回
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
*/
Integer x = Integer.valueOf(127);
Integer y = new Integer(127);
Integer z = Integer.valueOf(127);
Integer w = new Integer(127);
System.out.println(x.equals(y)); // true
System.out.println(x == y); // false
System.out.println(x == z); // true
System.out.println(w == x); // false
System.out.println(w == y); // fasle
Integer x1 = Integer.valueOf(200);
Integer x2 = Integer.valueOf(200);
System.out.println(x1 == x2); // false
}
}
* 定义一个接口:ITeacherDao
* 目标对象TeacherDAO实现接口ITeacherDAO
* 使用静态代理方式,就需要在代理对象TeacherDAOProxy中也实现ITeacherDAO
* 调用的时候通过调用代理对象的方法来调用目标对象
* 特别提醒:代理对象与目标对象要实现相同的接口,然后通过调用相同的方法来调用目标对象的方法。
public class StaticProxyCase {
public static void main(String[] args) {
// 创建被代理对象
TeacherDao teacherDao = new TeacherDao();
// 创建代理对象,同时将被代理对象传递给代理对象
TeacherDaoProxy proxy = new TeacherDaoProxy(teacherDao);
// 通过代理对象,调用到被代理对象的方法
proxy.teach();
}
}
interface ITeacherDao {
void teach();
}
class TeacherDao implements ITeacherDao {
@Override
public void teach() {
System.out.println("老师在上课...");
}
}
/**
* 代理对象
*/
class TeacherDaoProxy implements ITeacherDao {
private ITeacherDao target;
TeacherDaoProxy(ITeacherDao target) {
this.target = target;
}
@Override
public void teach() {
System.out.println("开始代理...");
target.teach();
System.out.println("结束代理...");
}
}
static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
public class JDKDynamicProxyCase {
public static void main(String[] args) {
JDKProxyFactory proxy = new JDKProxyFactory(new TeacherDao());
ITeacherDao teacherDao = (ITeacherDao) proxy.getProxyInstance();
System.out.println("teacherDao = " + teacherDao + ", teacherDao.getClass = " + teacherDao.getClass());
// class com.atguigu.dp.L11Proxy.$Proxy0 内存中动态生成了代理对象
teacherDao.teach();
}
}
class JDKProxyFactory {
private Object target;
JDKProxyFactory(Object target) {
this.target = target;
}
/**
* public static Object newProxyInstance(ClassLoader loader,
* Class>[] interfaces,
* InvocationHandler h)
* 1、loader:指定当前目标对象使用的类加载器,获取加载器的方法固定
* 2、interfaces:目标对象实现的接口类型,使用泛型确定类型
* 3、h:事件处理,执行目标对象方法时,会触发事情处理器方法,会把当前执行的目标对象方法作为参数传入
*/
public Object getProxyInstance() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("JDK动态代理 Before...");
Object result = method.invoke(target, args);
System.out.println("JDK动态代理 After...");
return result;
}
});
}
}
public class CglibDynamicProxyCase {
public static void main(String[] args) {
// 创建目标对象
StudentDao target = new StudentDao();
// 获取代理对象,并将目标对象传递给代理对象
StudentDao studentDao = (StudentDao) new CglibProxyFactory(target).getProxyInstance();
// 执行代理对象的方法
studentDao.study();
}
}
class StudentDao {
public void study() {
System.out.println("学生学习中...");
}
}
class CglibProxyFactory implements MethodInterceptor {
private Object target;
CglibProxyFactory(Object target) {
this.target = target;
}
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("CGLib动态代理 Before...");
Object result = method.invoke(target, args);
System.out.println("CGLib动态代理 After...");
return result;
}
public Object getProxyInstance() {
// 1、创建一个工具类
Enhancer enhancer = new Enhancer();
// 2、设置父类
enhancer.setSuperclass(target.getClass());
// 3、设置回调函数
enhancer.setCallback(this);
// 4、创建子类对象,即代理对象
return enhancer.create();
}
}