设计模式
设计模式分类
A
创建型设计模式
创建型类模式和创建型对象模式的区别
大体思想
简单工厂模式
package designPattern;
/**
* 简单工厂模式
*/
public class simpleFactory {
public static void main(String[] args) {
Product a = Factory.createProduct("A");
a.info();
Product b = Factory.createProduct("B");
b.info();
Product c = Factory.createProduct("c");
c.info();
}
}
//
class Factory{
public static Product createProduct(String type){
Product product = null;
switch (type){
case "A":
product = new ProductA();
break;
case "B":
product = new ProductB();
break;
default:
System.out.println("没有"+type+"类型的产品");
break;
}
return product;
}
}
abstract class Product{
public abstract void info();
}
class ProductA extends Product{
@Override
public void info() {
System.out.println("产品的信息:A");
}
}
class ProductB extends Product {
@Override
public void info() {
System.out.println("产品的信息:B");
}
}
存在的问题:违反了开放封闭原则。。。(对扩展开放,对修改封闭)
(每加一个产品(扩展),则需要修改工厂代码(修改))
工厂方法模式
上午题考察意图,下午题考察代码填空。。。
左边是简单工厂模式,右边是工厂模式。。
就是把工厂用接口定义,让其子类决定实例化哪个类(使一个类的实例化延迟到其子类)
父类 对象名 = new 子类();
编译看左边,运行看右边
多态的形式
package designPattern.factoryMethod;
public class factoryMethod {
public static void main(String[] args) {
Factory facA = new FactoryA();
Product producta = facA.createProduct();
producta.info();
Factory facB = new FactoryB();
Product productb= facB.createProduct();
productb.info();
}
}
interface Factory{
public Product createProduct();
}
class FactoryA implements Factory{
@Override
public Product createProduct() {
return new ProductA();
}
}
class FactoryB implements Factory{
@Override
public Product createProduct() {
return new ProductB();
}
}
//接口中的方法都是抽象方法,不用重复定义abstract了。。。
interface Product{
public void info();
}
class ProductA implements Product{
@Override
public void info() {
System.out.println("产品的信息:A");
}
}
class ProductB implements Product{
@Override
public void info() {
System.out.println("产品的信息:B");
}
}
工厂方法的概念
抽象工厂模式
工厂中创建多类产品。。
package designPattern.abstractFactory;
public class abstractFactory {
public static void main(String[] args) {
Factory factorya = new FactoryA();
System.out.println("工厂A创建产品---------------");
ProductA aa = factorya.createProductA();
aa.info();
ProductB ab = factorya.createProductB();
ab.info();
System.out.println("工厂B创建产品------------------");
Factory factoryb = new FactoryB();
ProductA ba = factoryb.createProductA();
ba.info();
ProductB bb = factoryb.createProductB();
bb.info();
}
}
//工厂
interface Factory{
public ProductA createProductA();
public ProductB createProductB();
}
//工厂A
class FactoryA implements Factory{
@Override
public ProductA createProductA() {
return new ProductA1();
}
@Override
public ProductB createProductB() {
return new ProductB1();
}
}
//工厂B
class FactoryB implements Factory{
@Override
public ProductA createProductA() {
return new ProductA2();
}
@Override
public ProductB createProductB() {
return new ProductB2();
}
}
//接口中的方法都是抽象方法,不用重复定义abstract了。。。
//产品A
interface ProductA{
public void info();
}
class ProductA1 implements ProductA{
@Override
public void info() {
System.out.println("产品的信息:A1");
}
}
class ProductA2 implements ProductA{
@Override
public void info() {
System.out.println("产品的信息:A2");
}
}
//接口中的方法都是抽象方法,不用重复定义abstract了。。。
//产品B
interface ProductB{
public void info();
}
class ProductB1 implements ProductB{
@Override
public void info() {
System.out.println("产品的信息:B1");
}
}
class ProductB2 implements ProductB{
@Override
public void info() {
System.out.println("产品的信息:B2");
}
}
c
工厂模式和抽象工厂模式区分:
工厂模式
抽象工厂模式
D
B
生成器模式
package designPattern.builderMode;
import java.util.ArrayList;
import java.util.List;
public class builderMode {
public static void main(String[] args) {
Director director = new Director();
Builder builder1 = new Builder1();
director.Construct(builder1);
Product product = builder1.getResult();
product.show();
Builder builder2 = new Builder2();
director.Construct(builder2);
Product product2 = builder2.getResult();
product2.show();
}
}
//导演
class Director{
public void Construct(Builder builder){
builder.BuilderPart();
}
}
//生成器
abstract class Builder{
public abstract void BuilderPart();
public abstract Product getResult();
}
class Builder1 extends Builder{
Product product = new Product();
@Override
public void BuilderPart() {
product.Add("A");
product.Add("B");
product.Add("C");
product.Add("D");
product.Add("E");
product.Add("F");
}
@Override
public Product getResult() {
return product;
}
}
class Builder2 extends Builder{
Product product = new Product();
@Override
public void BuilderPart() {
product.Add("A");
product.Add("B");
product.Add("C");
}
@Override
public Product getResult() {
return product;
}
}
//产品和组件
class Product{
List<String> parts = new ArrayList<>();
public void Add(String part){
parts.add(part);
}
public void show(){
System.out.println("产品的组成: ");
for (String s : parts){
System.out.print(s+" ");
}
System.out.println("\n");
}
}
相同的构建过程,可以创建不同的表示。。。
B
c
A
A
A
c
a
D
原型模式
package designPattern.prototypeModel;
public class prototypeModel {
public static void main(String[] args) {
ConcretePrototype1 concretePrototype1 = new ConcretePrototype1(2023,528);
System.out.println(concretePrototype1.getId()+" "+concretePrototype1.getPrice());
ConcretePrototype1 copy = (ConcretePrototype1)concretePrototype1.Clone();
System.out.println(copy.getId()+" "+copy.getPrice());
}
}
interface Prototype{
public Object Clone();
}
class ConcretePrototype1 implements Prototype{
private int id;
private int price;
public ConcretePrototype1() {
}
public ConcretePrototype1(int id, int price) {
this.id = id;
this.price = price;
}
public int getId() {
return id;
}
public int getPrice() {
return price;
}
@Override
public Object Clone() {
ConcretePrototype1 concretePrototype1 = new ConcretePrototype1();
concretePrototype1.id=this.id;
concretePrototype1.price=this.price;
return concretePrototype1;
}
}
单例模式
package designPattern.singletonMode;
public class singletonMode {
public static void main(String[] args) {
// Singleton singleton = new Singleton();
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
Singleton singleton3 = Singleton.getInstance();
Singleton singleton4 = Singleton.getInstance();
System.out.println(singleton1.getNumber()+" "+singleton2.getNumber()+" "+singleton3.getNumber()+" "+singleton4.getNumber());
}
}
class Singleton{
private int number = 2022;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
//私有构造方法。。(在类外面就不能使用new实例化对象了。。。。)
private Singleton(){}
//仅有一个实例 (只new了一次对象。。。)
private static Singleton instance = new Singleton();
//全局访问点(获得唯一的实例。。)
public static Singleton getInstance(){
return instance;
}
}
都是同一个实例。。。
D
C
d
结构型设计模式
适配器模式
package designPattern.adapterMode;
public class adapterMode {
public static void main(String[] args) {
Target target = new Adapter();
target.Request();
}
}
class Target{
public void Request(){
System.out.println("usb数据线接口");
}
}
//适配器 (usb转type c)
//多态了。。(重写Request方法)
class Adapter extends Target{
private Adaptee typec = new Adaptee();
@Override
public void Request() {
typec.SpecificRequest();
}
}
class Adaptee{
public void SpecificRequest(){
System.out.println("Type-c数据线接口");
}
}
A
桥接模式
需要解耦合。。
大大降低了类的数目(原本111个类,现在22个)
package designPattern.bridgeMode;
public class bridgeMode {
public static void main(String[] args) {
Product productA = new ProductA();
productA.setName("产品A");
Color red = new Red();
Color blue = new Blue();
productA.setColor(red);
productA.Operation();
productA.setColor(blue);
productA.Operation();
}
}
//产品
abstract class Product{
private String name;
protected Color color;
public String getName() {
return name;
}
public Color getColor() {
return color;
}
public void setName(String name) {
this.name = name;
}
public void setColor(Color color) {
this.color = color;
}
//操作根据具体的产品再来定义。。。
public abstract void Operation();
}
class ProductA extends Product{
@Override
public void Operation() {
color.OperationImp(this.getName());
}
}
//颜色
interface Color{
public void OperationImp(String name);
}
class Red implements Color{
@Override
public void OperationImp(String name) {
System.out.println(name+": 红色");
}
}
class Blue implements Color{
@Override
public void OperationImp(String name) {
System.out.println(name+": 蓝色");
}
}
A
D
d
A
b
a
C
D
A
D
组合模式
组合模式概念
定义初始的组合文件(文件夹),文件,文件夹。。
package designPattern.combinationMode;
public class combinationMode {
public static void main(String[] args) {
AbstractFile folderA = new Folder("我是folderA");
folderA.printName();
AbstractFile fileA = new File("我是fileA");
fileA.printName();
}
}
abstract class AbstractFile{
protected String name;
public void printName(){
System.out.println(name);
}
}
class Folder extends AbstractFile{
public Folder(String name){
this.name = name;
}
}
class File extends AbstractFile{
public File(String name){
this.name = name;
}
}
再进行详细的添加,删除,,,
组合模式添加和删除代码实现
package designPattern.combinationMode;
import java.util.ArrayList;
import java.util.List;
public class combinationMode {
public static void main(String[] args) {
AbstractFile root = new Folder("root");
AbstractFile folderA = new Folder("我是folderA");
folderA.printName();
AbstractFile fileA = new File("我是fileA");
fileA.printName();
System.out.println(root.Add(folderA));
System.out.println(root.Add(fileA));
}
}
abstract class AbstractFile{
protected String name;
public void printName(){
System.out.println(name);
}
//public abstract void Add(AbstractFile file);
public abstract boolean Add(AbstractFile file);
//public abstract void Remove(AbstractFile file);
public abstract boolean Remove(AbstractFile file);
}
class Folder extends AbstractFile{
private List<AbstractFile> childrenLIst = new ArrayList<AbstractFile>();
public Folder(String name){
this.name = name;
}
@Override
public boolean Add(AbstractFile file) {
return childrenLIst.add(file);
}
@Override
public boolean Remove(AbstractFile file) {
return childrenLIst.remove(file);
}
}
class File extends AbstractFile{
public File(String name){
this.name = name;
}
@Override
public boolean Add(AbstractFile file) {
return false;
}
@Override
public boolean Remove(AbstractFile file) {
return false;
}
}
再进行遍历的定义。。
组合模式遍历代码实现
package designPattern.combinationMode;
import java.util.ArrayList;
import java.util.List;
public class combinationMode {
public static void main(String[] args) {
AbstractFile root = new Folder("root");
AbstractFile folderA = new Folder("我是folderA");
AbstractFile folderB = new Folder("我是folderB");
AbstractFile fileC = new File("fileC");
AbstractFile fileD = new File("fileD");
AbstractFile fileE = new File("fileE");
root.Add(folderA);
root.Add(folderB);
root.Add(fileC);
folderA.Add(fileD);
folderA.Add(fileE);
print(root);
}
//遍历打印所由的元素。。
static void print(AbstractFile file){
//打印当前根节点
file.printName();
List<AbstractFile> chiidrenList = file.getChildren();
//退出条件
if(chiidrenList==null) return;
//遍历根节点(递归调用)
for (AbstractFile children :chiidrenList){
print(children);
}
}
}
abstract class AbstractFile{
protected String name;
public void printName(){
System.out.println(name);
}
//public abstract void Add(AbstractFile file);
public abstract boolean Add(AbstractFile file);
//public abstract void Remove(AbstractFile file);
public abstract boolean Remove(AbstractFile file);
public abstract List<AbstractFile> getChildren();
}
class Folder extends AbstractFile{
private List<AbstractFile> childrenLIst = new ArrayList<AbstractFile>();
public Folder(String name){
this.name = name;
}
@Override
public boolean Add(AbstractFile file) {
return childrenLIst.add(file);
}
@Override
public boolean Remove(AbstractFile file) {
return childrenLIst.remove(file);
}
@Override
public List<AbstractFile> getChildren() {
return childrenLIst;
}
}
class File extends AbstractFile{
public File(String name){
this.name = name;
}
@Override
public boolean Add(AbstractFile file) {
return false;
}
@Override
public boolean Remove(AbstractFile file) {
return false;
}
@Override
public List<AbstractFile> getChildren() {
return null;
}
}
C
d
a
C
a
C
b
a
装饰器模式
装饰器模式概念
装饰器模式代码实现
package designPattern.decoratorMode;
public class decoratorMode {
public static void main(String[] args) {
Person tom = new Student("tom");
tom.Operation();
System.out.println("---------------");
Decorator decorator = new DecoratorA(tom);
decorator.Operation();
}
}
abstract class Person{
protected String name;
public abstract void Operation();//职责
}
class Student extends Person{
public Student(String name) {
this.name = name;
}
@Override
public void Operation() {
System.out.println(name+"的职责是学习");
}
}
abstract class Decorator extends Person{
//维持一个指向Component对象(Person)的指针
protected Person person;
}
class DecoratorA extends Decorator{
public DecoratorA(Person person) {
this.person = person;
}
@Override
public void Operation() {
person.Operation();//原本的职责
System.out.println("A装饰器添加一个新职责。。");
}
}
Person是Decorator的父类,因此,改进后:
package designPattern.decoratorMode;
public class decoratorMode {
public static void main(String[] args) {
Person tom = new Student("tom");
tom.Operation();
System.out.println("---------------");
tom = new DecoratorA(tom);
tom.Operation();
}
}
abstract class Person{
protected String name;
public abstract void Operation();//职责
}
class Student extends Person{
public Student(String name) {
this.name = name;
}
@Override
public void Operation() {
System.out.println(name+"的职责是学习");
}
}
abstract class Decorator extends Person{
//维持一个指向Component对象(Person)的指针
protected Person person;
}
class DecoratorA extends Decorator{
public DecoratorA(Person person) {
this.person = person;
}
@Override
public void Operation() {
person.Operation();//原本的职责
System.out.println("A装饰器添加一个新职责。。");
}
}
再套一层。。
对象链如下:
package designPattern.decoratorMode;
public class decoratorMode {
public static void main(String[] args) {
Person tom = new Student("tom");
tom.Operation();
System.out.println("---------------");
tom = new DecoratorA(tom);
tom = new DecoratorA((tom));
tom.Operation();
//对象链方法
System.out.println("---------------");
Person jack = new Student("jack");
jack= new DecoratorA(new DecoratorA(new Student("jack")));
jack.Operation();
}
}
abstract class Person{
protected String name;
public abstract void Operation();//职责
}
class Student extends Person{
public Student(String name) {
this.name = name;
}
@Override
public void Operation() {
System.out.println(name+"的职责是学习");
}
}
abstract class Decorator extends Person{
//维持一个指向Component对象(Person)的指针
protected Person person;
}
class DecoratorA extends Decorator{
public DecoratorA(Person person) {
this.person = person;
}
@Override
public void Operation() {
person.Operation();//原本的职责
System.out.println("A装饰器添加一个新职责。。");
}
}
装饰器模式代码调用过程
D
外观模式
package designPattern.facadeMode;
public class facadeMode {
public static void main(String[] args) {
Facade facade = new Facade();
facade.methodA();
facade.methodB();
facade.methodC();
}
}
class Facade{
SubSystemOne subSystemOne;
SubSystemTwo subSystemTwo;
SubSystemThree subSystemThree;
public Facade(){
subSystemOne = new SubSystemOne();
subSystemTwo = new SubSystemTwo();
subSystemThree = new SubSystemThree();
}
public void methodA(){
subSystemOne.methodOne();
}
public void methodB(){
subSystemTwo.methodTwo();
}
public void methodC(){
subSystemThree.methodThree();
}
}
class SubSystemOne{
public void methodOne(){
System.out.println("执行子系统1的功能");
}
}
class SubSystemTwo{
public void methodTwo(){
System.out.println("执行子系统2的功能");
}
}
class SubSystemThree{
public void methodThree(){
System.out.println("执行子系统3的功能");
}
}
C
D
B
D
享元模式
享元模式概念
享元模式代码实现
棋子的例子
package designPattern.flyWeightMode;
//棋子的例子
public class flyWeightMode {
public static void main(String[] args) {
PieceFactory factory = new PieceFactory();
Piece whitePiece1 = factory.getPiece(0);
System.out.println(whitePiece1);
Piece whitePiece2 = factory.getPiece(0);
System.out.println(whitePiece2);
Piece whitePiece3 = factory.getPiece(0);
System.out.println(whitePiece3);
Piece blackPiece1 = factory.getPiece(1);
System.out.println(blackPiece1);
Piece blackPiece2 = factory.getPiece(1);
System.out.println(blackPiece2);
Piece blackPiece3 = factory.getPiece(1);
System.out.println(blackPiece3);
}
}
class PieceFactory{
//只生成两个对象,后面都共享这俩。。
private Piece[] pieces = {new WhitePiece(),new BlackPiece()};
public Piece getPiece(int key){
if (key==0)return pieces[0];
else if(key==1) return pieces[1];
else return null;
}
}
//将x,y分离。。
abstract class Piece{
protected String color;
public abstract void draw(int x,int y);
}
class WhitePiece extends Piece{
public WhitePiece(){
this.color = "white";
}
@Override
public void draw(int x, int y) {
System.out.println("颜色是:"+color+"x位置:"+x+"y位置"+y);
}
}
class BlackPiece extends Piece{
public BlackPiece(){
this.color = "black";
}
@Override
public void draw(int x, int y) {
System.out.println("颜色是:"+color+"x位置:"+x+"y位置"+y);
}
}
圆的例子:
package designPattern.flyWeightMode2;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
//画圆的例子
public class flyWeightMode2 {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Random random = new Random();
String[] colors = {"红色","绿色","蓝色","粉色","橙色"};
for (int i =1;i<10;i++){
int x = random.nextInt(colors.length);
Shape shape = factory.getShape(colors[x]);
System.out.println("第"+i+"个园");
shape.drow(random.nextInt(1000),random.nextInt(1000));
}
}
}
//生成圆的工厂
class ShapeFactory{
private Map<String ,Shape> map = new HashMap<String,Shape>();
public Shape getShape(String key){
if (map.containsKey(key)){
return map.get(key);
}else {
System.out.println("_______________创建一个新园型_______________:");
Shape shape = new Circle(key);
map.put(key,shape);//把颜色作为Key,原型作为shape
return shape;
}
}
}
abstract class Shape{
protected String color;
public abstract void drow(int x,int y);
}
class Circle extends Shape{
public Circle(String color){
this.color = color;
}
@Override
public void drow(int x, int y) {
System.out.println("颜色是:"+color+"x位置是:"+x+"y位置是"+y);
}
}
简化工厂代码的判断逻辑。。
package designPattern.flyWeightMode2;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
//画圆的例子
public class flyWeightMode2 {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Random random = new Random();
String[] colors = {"红色","绿色","蓝色","粉色","橙色"};
for (int i =1;i<10;i++){
int x = random.nextInt(colors.length);
Shape shape = factory.getShape(colors[x]);
System.out.println("第"+i+"个园");
shape.drow(random.nextInt(1000),random.nextInt(1000));
}
}
}
//生成圆的工厂
class ShapeFactory{
private Map<String ,Shape> map = new HashMap<String,Shape>();
public Shape getShape(String key){
if (!map.containsKey(key)){
map.put(key,new Circle(key));
System.out.println("创建一个新圆。。");
}
return map.get(key);
}
}
abstract class Shape{
protected String color;
public abstract void drow(int x,int y);
}
class Circle extends Shape{
public Circle(String color){
this.color = color;
}
@Override
public void drow(int x, int y) {
System.out.println("颜色是:"+color+"x位置是:"+x+"y位置是"+y);
}
}
B
代理模式
package designPattern.proxyMode;
public class proxyMode {
public static void main(String[] args) {
RealSubject realSubject = new RealSubject();
Proxy proxy = new Proxy(realSubject);
proxy.buy();
}
}
interface Subject{
public void buy();
}
//代理
class Proxy implements Subject{
protected RealSubject realSubject;
public Proxy(RealSubject realSubject){
this.realSubject = realSubject;
}
@Override
public void buy() {
System.out.println("代理办理付钱之前的手续");
realSubject.buy();
System.out.println("代理办理付款后的手续");
}
}
//实体
class RealSubject implements Subject{
@Override
public void buy() {
System.out.println("付款");
}
}
B
行为型设计模式
责任链模式
package designPattern.chainOfResponsibility;
public class chainOfResponsibility {
public static void main(String[] args) {
Handler fudaoyuan = new FuDaoYuan();
Handler yuanzhang = new YanZhang();
Handler xiaozhang = new XiaoZhang();
fudaoyuan.setNext(yuanzhang);
yuanzhang.setNext(xiaozhang);
fudaoyuan.HandlerRequest(28);
}
}
abstract class Handler{
//指向后继节点的指针
protected Handler next;
public void setNext(Handler next ){
this.next = next;
}
public abstract void HandlerRequest(int request);
}
class FuDaoYuan extends Handler{
@Override
public void HandlerRequest(int request) {
if(request<=7){
System.out.println("辅导员审批通过");
}else {
if(next!=null){
//调用后继节点。。
next.HandlerRequest(request);
}else {
System.out.println("无法审批");
}
}
}
}
class YanZhang extends Handler{
@Override
public void HandlerRequest(int request) {
if(request<=15){
System.out.println("院长审批通过");
}else {
if(next!=null){
//调用后继节点。。
next.HandlerRequest(request);
}else {
System.out.println("无法审批");
}
}
}
}
class XiaoZhang extends Handler{
@Override
public void HandlerRequest(int request) {
if(request<=30){
System.out.println("校长审批通过");
}else {
if(next!=null){
//调用后继节点。。
next.HandlerRequest(request);
}else {
System.out.println("无法审批");
}
}
}
}
命令模式
package designPattern.commandMode;
public class commandMode {
public static void main(String[] args) {
Tv tv = new Tv();
Command onCommand = new OnCommand(tv);
Command offCommand = new OffCommand(tv);
Invoker invoker = new Invoker();
invoker.setCommand(onCommand);
invoker.call();
System.out.println("--------------");
invoker.setCommand(offCommand);
invoker.call();
}
}
//请求者(整体)
class Invoker{
private Command command;
public void setCommand(Command command){
this.command = command;
}
//调用命令。。。
public void call(){
command.Execute();
}
}
//命令接口(部分)
interface Command{
public void Execute();//执行命令
}
//具体的命令
//开机命令
class OnCommand implements Command{
private Tv tv;
public OnCommand(Tv tv){
this.tv = tv;
}
@Override
public void Execute() {
tv.OnAction();
}
}
//关机命令
class OffCommand implements Command{
private Tv tv;
public OffCommand(Tv tv){
this.tv = tv;
}
@Override
public void Execute() {
tv.OffAction();
}
}
//接收者
//电视机(开机行为和关机行为)
class Tv{
public void OnAction(){
System.out.println("电视机开机了....");
}
public void OffAction(){
System.out.println("电视机关机了...");
}
}
A
解释器模式
package designPattern.InterpreterPattern;
import java.util.HashSet;
import java.util.Set;
public class InterpreterPattern {
public static void main(String[] args) {
Context context = new Context();
context.check("A区的开发人员");
context.check("B区的调试人员");
context.check("C区的测试人员");
System.out.println("==========");
context.check("D区的程序员");
context.check("D区的测试员");
context.check("A区的程序员");
}
}
class Context {
private String[] regions = {"A区", "B区", "C区"};
private String[] persons = {"开发人员", "测试人员", "调试人员"};
private NonterminalExprssion nonterminal;
public Context() {
TerminalExpression region = new TerminalExpression(regions);
TerminalExpression person = new TerminalExpression(persons);
nonterminal = new NonterminalExprssion(region, person);
}
public void check(String info) {
boolean bool = nonterminal.Interpret(info);
if (bool) {
System.out.println("识别成功");
} else {
System.out.println("识别失败");
}
}
}
interface Expression {
public boolean Interpret(String info);
}
//非终端解释器
//将字符串拆分,并调用终端解释器来解释
class NonterminalExprssion implements Expression {
private TerminalExpression region;
private TerminalExpression person;
public NonterminalExprssion(TerminalExpression region, TerminalExpression person) {
this.region = region;
this.person = person;
}
@Override
public boolean Interpret(String info) {
String[] str = info.split("的");
// B区的调试人员 --> str = {"B区", "调试人员"}
return region.Interpret(str[0]) && person.Interpret(str[1]);
}
}
//终端解释器
//只能识别xxx区,xxx人员
class TerminalExpression implements Expression {
private Set<String> set = new HashSet<>();
public TerminalExpression(String[] data) {
// for (遍历对象类型 对象名 : 遍历对象)
for (String str : data) {
set.add(str);
}
}
@Override
public boolean Interpret(String info) {
return set.contains(info);
}
}
迭代器模式
package designPattern.IteratorPattern;
import java.util.ArrayList;
import java.util.List;
public class IteratorPattern {
public static void main(String[] args) {
BookAggregate bookAggregate = new BookAggregate();
String[] books = {"数据结构", "操作系统", "计算机网络", "计算机组成原理"};
double[] prices = {10.24, 20.48, 40.96, 81.92};
for (int i = 0; i < 4; i ++ ) {
bookAggregate.Add(new Book(books[i], prices[i]));
}
Iterator bookIterator = bookAggregate.CreateIterator();
while (bookIterator.hasNext()) {
Book book = (Book) bookIterator.next();
System.out.println(book.getName() + " " + book.getPrice());
}
}
}
//迭代器
interface Iterator {
public boolean hasNext();
public Object next();
}
//图书迭代器
class BookIterator implements Iterator {
private int index; //跟踪当前位置
private BookAggregate bookAggregate;
public BookIterator(BookAggregate bookAggregate) {
this.index = 0;
this.bookAggregate = bookAggregate;
}
@Override
public boolean hasNext() {
if (index < bookAggregate.getSize()) {
return true;
} else {
return false;
}
}
@Override
public Object next() {
Object obj = bookAggregate.get(index);
index ++ ;
return obj;
}
}
//聚合
interface Aggregate {
public Iterator CreateIterator();
}
//图书聚合
class BookAggregate implements Aggregate {
private List<Book> list = new ArrayList<Book>();
public void Add(Book book) {
list.add(book);
}
public Book get(int index) {
return list.get(index);
}
public int getSize() {
return list.size();
}
@Override
public Iterator CreateIterator() {
return new BookIterator(this);
}
}
class Book {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
中介者模式
不使用中介者
如果1号人想和其他人通信,则需要在其内部定义其他人的引用(耦合紧密)
使用中介者模式:
每个同事只需要定义一个指向中介者的指针
在中介者里面定义了指向所有员工的指针,(相比之前,解耦合了)
中介者模式代码实现
package designPattern.MediatorPattern;
public class MediatorPattern {
public static void main(String[] args) {
//中介者
ConcreteMediator mediator = new ConcreteMediator();
//同事
Colleague1 colleague1 = new Colleague1(mediator);
Colleague2 colleague2 = new Colleague2(mediator);
mediator.setColleague1(colleague1);
mediator.setColleague2(colleague2);
colleague1.sendMessage("软考加油");
colleague2.sendMessage("祝大家软考顺利通过!");
}
}
//同事接口
abstract class Colleague {
//指向中介者的指针
protected Mediator mediator;
}
//同事A
class Colleague1 extends Colleague {
public Colleague1(Mediator mediator) {
this.mediator = mediator;
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
public void Notify(String message) {
System.out.println("同事1收到消息:" + message);
}
}
//同事B
class Colleague2 extends Colleague {
public Colleague2(Mediator mediator) {
this.mediator = mediator;
}
public void sendMessage(String message) {
mediator.sendMessage(message, this);
}
public void Notify(String message) {
System.out.println("同事2收到消息:" + message);
}
}
//中介者
abstract class Mediator {
public abstract void sendMessage(String message, Colleague colleague);
}
//具体中介者
class ConcreteMediator extends Mediator {
//指向同事的指针
private Colleague1 colleague1;
private Colleague2 colleague2;
public void setColleague1(Colleague1 colleague1) {
this.colleague1 = colleague1;
}
public void setColleague2(Colleague2 colleague2) {
this.colleague2 = colleague2;
}
/**
*
* @param message 要发送的信息内容
* @param colleague 指定发送者是谁 .(this)
*/
public void sendMessage(String message, Colleague colleague) {
if (colleague == colleague1) {
colleague2.Notify(message); // 让同事2收到消息
} else {
colleague1.Notify(message); // 让同事1收到消息
}
}
}
d
c
d
备忘录模式
package designPattern.MementoPattern;
import java.util.ArrayList;
import java.util.List;
public class MementoPattern {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
Originator originator = new Originator();
originator.setState("1024");
Memento backup1 = originator.createMemento();
caretaker.addMemento(backup1);
originator.setState("2048");
Memento backup2 = originator.createMemento();
caretaker.addMemento(backup2);
originator.setState("4096");
Memento backup3 = originator.createMemento();
caretaker.addMemento(backup3);
System.out.println(originator.getState());
caretaker.showMemento();
Memento memento1 = caretaker.getMemento(2);
originator.setMemento(memento1);
System.out.println("根据第2次备份还原之后的状态为:" + originator.getState());
}
}
//原发器根据需要决定备忘录存储原发器哪些内部状态
class Originator { // 原发器
private String state;
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public Memento createMemento() {
return new Memento(state);
}
public void setMemento(Memento memento) {
state = memento.getState();
}
}
//存储原发器对象的内部状态
class Memento { // 备忘录
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
//负责保存备忘录
class Caretaker { // 管理者
private List<Memento> mementoList = new ArrayList<>();
public void addMemento(Memento memento) {
mementoList.add(memento);
}
public Memento getMemento(int index) {
// 判断参数是否合法
if (index >= 1 && index <= mementoList.size()) {
return mementoList.get(index - 1);
}
return null;
}
public void showMemento() {
int cnt = 1;
// for (遍历对象类型 对象名 : 遍历对象)
for (Memento memento : mementoList) {
System.out.println("第" + cnt + "次备份,状态为:" + memento.getState());
cnt ++ ;
}
}
}
观察者模式
package designPattern.ObserverPattern;
import java.util.ArrayList;
import java.util.List;
public class ObserverPattern {
public static void main(String[] args) {
//up主(目标A)
Subject subjectA = new ConcreteSubject("目标A");
//用户(张三,李四。王五)
//用户都关注了up主
Observer observerB = new ConcreteObserver("张三", subjectA);
Observer observerC = new ConcreteObserver("李四", subjectA);
Observer observerD = new ConcreteObserver("王五", subjectA);
subjectA.setState("更新了");
System.out.println("======================================");
subjectA.Detach(observerD);
subjectA.setState("停更了");
}
}
interface Subject { // 目标
public void Attach(Observer observer); // 添加观察者
public void Detach(Observer observer); // 删除观察者
public void Notify(); // 状态改变后 通知所有观察者
public void setState(String state); // 设置状态(改变状态)
public String getState(); // 获取状态
}
class ConcreteSubject implements Subject {
private String name;
private String state;
private List<Observer> observerList;
public ConcreteSubject(String name) {
state = "未更新";
this.name = name;
observerList = new ArrayList<Observer>();
}
public void setState(String state) {
this.state = state;
System.out.println(name + "的状态发生变化,变化后的状态为:" + state);
//当up主跟新了,通知关注他的用户
Notify();
}
public String getState() {
return state;
}
public void Attach(Observer observer) {
observerList.add(observer);
}
public void Detach(Observer observer) {
observerList.remove(observer);
}
public void Notify() {
// for (遍历对象类型 对象名 : 遍历对象)
for (Observer observer : observerList) {
observer.update();
}
}
}
interface Observer { // 观察者接口
public void update(); // 收到通知 更新观察者的状态
}
class ConcreteObserver implements Observer {
private String name;
private String state;
//指向up主的引用
private Subject subject;
public ConcreteObserver(String name, Subject subject) {
this.name = name;
//指向当前用户关注的up主
this.subject = subject;
//将当前的用户添加到up主的用户列表中
subject.Attach(this);
//保持up主的状态和用户状态一致
state = subject.getState();
}
@Override
public void update() {
System.out.println(name + "收到通知");
state = subject.getState(); // 让当前观察者的状态 和 改变了状态之后的目标的状态保持一致
System.out.println(name + "改变后的状态为:" + state);
}
}
d
a(一个up主可以有多个粉丝)
d
b
c
b
d
c
a
b
d
状态模式
有货的状态:行为(售卖)
无货的状态:行为(补货)
public class StatePattern{
public static void main(String[] args) {
Context context = new Context(); // count:3
System.out.println(context.getState());
context.Request(); // 购买一个饮料 count = 2
context.Request(); // 购买一个饮料 count = 1
context.Request(); // 购买一个饮料 count = 0
System.out.println(context.getState());
context.Request(); // 无货 等待补货 补货成功 count = 5
System.out.println(context.getState());
context.Request(); // 购买一个饮料 count = 4
System.out.println(context.getCount());
}
}
class Context { // 贩卖机
private int count;
private State state;
public Context() {
count = 3;
state = new StateA();
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public void Request() { // 购买一个饮料
state.Handle(this);
}
}
interface State {
public void Handle(Context context);
}
class StateA implements State { // 有货
@Override
public void Handle(Context context) {
int count = context.getCount();
if (count >= 1) {
System.out.println("购买成功!");
context.setCount(count - 1);
if (context.getCount() == 0) {
context.setState(new StateB());
}
} else {
System.out.println("购买失败!");
}
}
}
class StateB implements State { // 无货
@Override
public void Handle(Context context) {
int count = context.getCount();
if (count == 0) {
System.out.println("购买失败!等待补货");
context.setCount(5);
System.out.println("补货成功,请重新购买");
context.setState(new StateA());
}
}
}
d
c
a
b
b
d
c
策略模式
a
b
c
a
模板方法模式
package designPattern.TemplateMethodPattern;
public class TemplateMethodPattern{
public static void main(String[] args) {
// 父类名 对象名 = new 子类名();
Person student = new Student();
Person teacher = new Teacher();
student.TemplateMethod();
System.out.println("=====我是分割线=====");
teacher.TemplateMethod();
}
}
//抽象类(定义抽象的原语操作)
abstract class Person {
public void TemplateMethod() {
//一次性实现算法中不变的部分,并将可变的行为留给子类来实现
//各个子类的公共行为被提取出来,并集中到一个公共的父类中,避免代码重复
//子类可以不改变算法的结构,即可重新定义某些特定的步骤
System.out.println("上课 去教室"); // 1
PrimitiveOperation1(); // 2
System.out.println("下课 离开教室"); // 3
PrimitiveOperation2(); // 4
}
public abstract void PrimitiveOperation1(); // 原语操作 1 :上课过程 学生 听课…… 老师 讲课
public abstract void PrimitiveOperation2(); // 原语操作 2 :作业 学生 写作业 提交作业…… 老师 批改作业 打分数
}
//具体类(重新定义)
class Student extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("学生:听课 学习 做笔记 提出问题");
}
@Override
public void PrimitiveOperation2() {
System.out.println("学生:写作业 提交作业");
}
}
//具体类
class Teacher extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("老师:上课 讲课 解答问题 布置作业");
}
@Override
public void PrimitiveOperation2() {
System.out.println("老师:批改作业 打分数");
}
}
访问者模式
访问者模式代码实现
package designPattern.VisitorPattern;
import java.util.ArrayList;
import java.util.List;
public class VisitorPattern {
public static void main(String[] args) {
PersonStructure structure = new PersonStructure();
Visitor1 visitor1 = new Visitor1();
System.out.println("访问者1的访问记录:");
structure.Accept(visitor1);
System.out.println("学生年龄的总和:" + visitor1.getStudentAgeSum() + " 老师年龄的总和:" + visitor1.getTeacherAgeSum());
System.out.println("=========================================");
Visitor2 visitor2 = new Visitor2();
System.out.println("访问者2的访问记录:");
structure.Accept(visitor2);
System.out.println("学生的最高成绩:" + visitor2.getMaxScore() + " 老师的最高工龄:" + visitor2.getMaxWorkYear());
}
}
//访问者接口
interface Visitor {
public void visitStudent(Student student); // 访问学生
public void visitTeacher(Teacher teacher); // 访问老师
}
//访问者1
class Visitor1 implements Visitor { // 访问者1 分别统计学生和老师的年龄总和
private int studentAgeSum = 0;
private int teacherAgeSum = 0;
public int getStudentAgeSum() {
return studentAgeSum;
}
public int getTeacherAgeSum() {
return teacherAgeSum;
}
@Override
public void visitStudent(Student student) {
System.out.println("访问者1访问学生:" + student.getName() + " 年龄:" + student.getAge());
studentAgeSum += student.getAge();
}
@Override
public void visitTeacher(Teacher teacher) {
System.out.println("访问者1访问老师:" + teacher.getName() + " 年龄:" + teacher.getAge());
teacherAgeSum += teacher.getAge();
}
}
//访问者2
class Visitor2 implements Visitor { // 访问者2 分别求出 学生的最高成绩 以及 老师的最高工龄
private int maxScore = -1;
private int maxWorkYear = -1;
public int getMaxScore() {
return maxScore;
}
public int getMaxWorkYear() {
return maxWorkYear;
}
@Override
public void visitStudent(Student student) {
System.out.println("访问者2访问学生:" + student.getName() + " 成绩:" + student.getScore());
maxScore = Math.max(maxScore, student.getScore());
}
@Override
public void visitTeacher(Teacher teacher) {
System.out.println("访问者2访问老师:" + teacher.getName() + " 工龄:" + teacher.getWorkYear());
maxWorkYear = Math.max(maxWorkYear, teacher.getWorkYear());
}
}
class PersonStructure {
private List<Person> personList = new ArrayList<Person>();
public PersonStructure() {
personList.add(new Student("张三", 20, 70));
personList.add(new Student("李四", 21, 80));
personList.add(new Student("王五", 22, 90));
personList.add(new Teacher("李老师", 26, 3));
personList.add(new Teacher("陈老师", 27, 4));
personList.add(new Teacher("刘老师", 28, 5));
}
public void Accept(Visitor visitor) {
// for (遍历对象类型 对象名 : 遍历对象)
for (Person person : personList) {
person.Accept(visitor);
}
}
}
//元素
abstract class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public abstract void Accept(Visitor visitor);
}
//具体元素
class Student extends Person {
private int score;
public Student(String name, int age, int score) {
super(name, age);
this.score = score;
}
public int getScore() {
return score;
}
@Override
public void Accept(Visitor visitor) {
visitor.visitStudent(this);
}
}
//具体元素
class Teacher extends Person {
private int workYear;
public Teacher(String name, int age, int workYear) {
super(name, age);
this.workYear = workYear;
}
public int getWorkYear() {
return workYear;
}
@Override
public void Accept(Visitor visitor) {
visitor.visitTeacher(this);
}
}
a
b
a
d
c
总和
c
d
b
b
d
c
a
d
c
a
d
b
a
c
d
d
a
d
a
d
c