goF23设计模式~思想学习笔记(一)
goF23设计模式~思想学习笔记(三)
结构型模式
-
适配器模式(Adapter Pattern): 将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
image.png
1.1类适配器
public class Voltage220v {
public int output220v (){
int scr = 220;
System.out.println("输出电压"+scr+"v");
return scr;
}
}
public interface Voltage5v {
int out5v();
}
public class VoltageAdapter extends Voltage220v implements Voltage5v{
@Override
public int out5v() {
int scr = output220v();
int desV = scr / 44;
return desV;
}
}
1.2对象适配器:修改VoltageAdapter把Voltage220v的对象聚合进来
image.png
public class VoltageAdapter implements Voltage5v {
Voltage220v voltage220v;
public VoltageAdapter(Voltage220v voltage220v) {
this.voltage220v = voltage220v;
}
@Override
public int out5v() {
int scr = voltage220v.output220v();
int desV = scr / 44;
return desV;
}
}
-
装饰模式(Decorator Pattern): 动态地给一个对象添加一些额外的职责。就扩展功能而言,它比生成子类方式更为灵活。
image.png
public class Drink {
String des;
float price;
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public void setPrice(float price) {
this.price = price;
}
//计算价格
public float cost(){
return price;
}
@Override
public String toString() {
return this.getClass() + "{" +
"des='" + getDes() + '\'' +
", price=" + cost() +
'}';
}
}
public class Coffee extends Drink {
}
public class ShortBlack extends Coffee {
public ShortBlack() {
setDes("ShortBlack");
setPrice(6.0f);
}
}
public class LongBlack extends Coffee {
public LongBlack() {
setDes("LongBlack");
setPrice(5.0f);
}
}
public class Decorator extends Drink {
Drink drink;
public Decorator(Drink drink) {
this.drink = drink;
}
@Override
public String getDes() {
return super.getDes() + "&&" + drink.getDes() + " ";
}
@Override
public float cost() {
return super.cost() + drink.cost();
}
}
public class Milk extends Decorator {
public Milk(Drink drink) {
super(drink);
setDes("Milk");
setPrice(2.0f);
}
}
public class Chocolate extends Decorator {
public Chocolate(Drink drink) {
super(drink);
setDes("Chocolate");
setPrice(3.0f);
}
}
public class Test {
public static void main(String[] args) {
Drink drink = new ShortBlack();
System.out.println(drink);
//加一分巧克力作料
drink = new Chocolate(drink);
System.out.println(drink);
//再添加一份巧克力作料
drink = new Chocolate(drink);
System.out.println(drink);
//添加一份牛奶作料
drink = new Milk(drink);
System.out.println(drink);
/*
class construction.decorator.ShortBlack{des='ShortBlack', price=6.0}
class construction.decorator.Chocolate{des='Chocolate&&ShortBlack ', price=9.0}
class construction.decorator.Chocolate{des='Chocolate&&Chocolate&&ShortBlack ', price=12.0}
class construction.decorator.Milk{des='Milk&&Chocolate&&Chocolate&&ShortBlack ', price=14.0}
*/
}
}
-
代理模式(Proxy Pattern): 为其他对象提供一个代理以控制对这个对象的访问。
3.1静态代理
image.png
public interface ITeacherDao {
void teach();
}
public class TeacherDao implements ITeacherDao {
@Override
public void teach() {
System.out.println("TeacherDao" + " teaching");
}
}
public class TeacherDaoProxy implements ITeacherDao {
private ITeacherDao target;
public TeacherDaoProxy(ITeacherDao target) {
this.target = target;
}
@Override
public void teach() {
//可以在此 做些事情...
target.teach();
}
}
public class Test {
public static void main(String[] args) {
//静态代理 接口变化 实现和代理都需要修改
ITeacherDao iTeacherDao = new TeacherDaoProxy(new TeacherDao());
iTeacherDao.teach();
}
}
3.2动态代理
image.png
public interface ITeacherDao {
void teach();
}
public class TeacherDao implements ITeacherDao {
@Override
public void teach() {
System.out.println("TeacherDao" + " teaching");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactory {
Object getProxyInstance(ITeacherDao target){
//Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
var obj = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target,args);
}
}
);
return obj;
}
}
public class Test {
public static void main(String[] args) {
//动态代理
ITeacherDao iTeacherDao = (ITeacherDao)new ProxyFactory().getProxyInstance(new TeacherDao());
iTeacherDao.teach();
}
}
-
外观模式(Facade Pattern): 为子系统中的一组接口提供一个一致的界面,Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
image.png
public class HomeFacade {
private DVDPlayer dvdPlayer;
private Projector projector;
private Stereo stereo;
private TheaterLight theaterLight;
HomeFacade(){
dvdPlayer = DVDPlayer.getInstance();
projector = Projector.getInstance();
stereo = Stereo.getInstance();
theaterLight = TheaterLight.getInstance();
}
void ready(){
dvdPlayer.on();
projector.on();
stereo.on();
theaterLight.on();
}
void play(){
dvdPlayer.play();
theaterLight.mid();
}
void pause(){
dvdPlayer.pause();
theaterLight.lighted();
}
void stop(){
dvdPlayer.off();
projector.off();
stereo.off();
theaterLight.off();
}
}
public interface Device {
default void on(){
System.out.println(this.getClass() + " on");
}
default void off(){
System.out.println(this.getClass() + " off");
}
}
public class DVDPlayer implements Device {
private DVDPlayer(){}
static private final DVDPlayer instance = new DVDPlayer();
static public DVDPlayer getInstance(){
return instance;
}
void play(){
System.out.println("DVDPlayer play");
}
void pause(){
System.out.println("DVDPlayer pause");
}
}
public class Projector implements Device {
private Projector(){}
static private final Projector instance = new Projector();
static public Projector getInstance(){
return instance;
}
}
public class TheaterLight implements Device {
private TheaterLight(){}
static private final TheaterLight instance = new TheaterLight();
static public TheaterLight getInstance(){
return instance;
}
void lighted(){
System.out.println("change lighted");
}
void mid(){
System.out.println("change mid");
}
}
public class Stereo implements Device {
private Stereo(){}
static private final Stereo instance = new Stereo();
static public Stereo getInstance(){
return instance;
}
}
-
桥接模式(Bridge Pattern): 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
image.png
public interface Brand {
String info();
}
public class Vivo implements Brand {
@Override
public String info() {
return "Vivo";
}
}
public class Xiaomi implements Brand {
@Override
public String info() {
return "Xiaomi";
}
}
abstract public class Phone {
Brand brand;
public Phone(Brand brand) {
this.brand = brand;
}
}
public class FoldedPhone extends Phone {
public FoldedPhone(Brand brand) {
super(brand);
}
@Override
public String toString() {
return "FoldedPhone{" +
"brand=" + brand +
'}';
}
}
public class UpRightPhone extends Phone {
public UpRightPhone(Brand brand) {
super(brand);
}
@Override
public String toString() {
return "UpRightPhone{" +
"brand=" + brand +
'}';
}
}
public class Test {
public static void main(String[] args) {
FoldedPhone foldedPhone = new FoldedPhone(new Vivo());
System.out.println(foldedPhone);
UpRightPhone upRightPhone = new UpRightPhone(new Vivo());
System.out.println(upRightPhone);
}
}
-
组合模式(Composite Pattern): 将对象组合成树形结构以表示“部分-整体”的层次结构。它使得客户对单个对象和复合对象的使用具有一致性。
image.png
abstract public class OrganizationComponent {
private String name;
private String des;
public OrganizationComponent(String name, String des) {
this.name = name;
this.des = des;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
void add(OrganizationComponent organizationComponent){
throw new UnsupportedOperationException();
}
void remove(OrganizationComponent organizationComponent){
throw new UnsupportedOperationException();
}
void print(){
var s = "" +
"name='" + name + '\'' +
", des='" + des + '\'' +
'}';
System.out.println(s);
}
}
public class University extends OrganizationComponent {
private List<OrganizationComponent> list = new ArrayList<OrganizationComponent>();
public University(String name, String des) {
super(name, des);
}
@Override
void add(OrganizationComponent organizationComponent) {
list.add(organizationComponent);
}
@Override
void remove(OrganizationComponent organizationComponent) {
list.remove(organizationComponent);
}
@Override
void print() {
System.out.println("-------University--------");
for (OrganizationComponent organizationComponent: list) {
organizationComponent.print();
}
}
}
public class College extends OrganizationComponent {
private List<OrganizationComponent> list = new ArrayList<OrganizationComponent>();
public College(String name, String des) {
super(name, des);
}
@Override
void add(OrganizationComponent organizationComponent) {
list.add(organizationComponent);
}
@Override
void remove(OrganizationComponent organizationComponent) {
list.remove(organizationComponent);
}
@Override
void print() {
System.out.println("-------College--------");
for (OrganizationComponent organizationComponent: list) {
organizationComponent.print();
}
}
}
public class Department extends OrganizationComponent {
public Department(String name, String des) {
super(name, des);
}
}
public class Test {
public static void main(String[] args) {
University university = new University("清华大学","一流大学");
College computerCollege = new College("计算机学院","计算机学院des");
computerCollege.add(new Department("计算机科学与技术","计算机科学与技术des"));
computerCollege.add(new Department("软件工程","软件工程des"));
College informationCollege = new College("信息学院","信息学院des");
informationCollege.add(new Department("通信专业","通信专业des"));
informationCollege.add(new Department("传输专业","传输专业des"));
university.add(computerCollege);
university.add(informationCollege);
university.print();
/*
-------University--------
-------College--------
name='计算机科学与技术', des='计算机科学与技术des'}
name='软件工程', des='软件工程des'}
-------College--------
name='通信专业', des='通信专业des'}
name='传输专业', des='传输专业des'}
*/
// computerCollege.print();
// informationCollege.print();
}
}
-
享元模式(Flyweight Pattern): 运用共享技术有效地支持大量细粒度的对象。
image.png
public class WebsiteFactory {
Map<String,Website> map = new HashMap();
Website getWebsiteCategory(String name){
if(!map.containsKey(name)){
map.put(name,new ConcreteWebsite(name));
}
return (Website) map.get(name);
}
public int size() {
return map.size();
}
}
public interface Website {
void use(User user);
}
public class ConcreteWebsite implements Website {
private String name;
public ConcreteWebsite(String name) {
this.name = name;
}
@Override
public void use(User user) {
System.out.println("网站发布形式:" + name + " " + user.getName() + "正在使用");
}
}
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Test {
public static void main(String[] args) {
WebsiteFactory websiteFactory = new WebsiteFactory();
Website website = websiteFactory.getWebsiteCategory("微博");
website.use(new User("小明"));
Website website2 = websiteFactory.getWebsiteCategory("微信");
website2.use(new User("小微"));
Website website3 = websiteFactory.getWebsiteCategory("微信");
website3.use(new User("小微2"));
System.out.println(websiteFactory.size());
/*
网站发布形式:微博 小明正在使用
网站发布形式:微信 小微正在使用
网站发布形式:微信 小微2正在使用
2
*/
}
}
网友评论