【中级软件设计师】—(针对上午题)二十三种设计模式(三十九)
一、设计模式的分类
背背背
1
二、创建型设计模式(5种)
三、简单工厂模式
简单工厂模式代码实现如下:
/**
* @author:CaiCai
* @date : 2023/4/26 9:11
*
*/
/*
简单工厂模式
* */
public class SimpleFactory {
public static void main(String[] args){
Product productA=Factory.createProduct("A");
productA.info();
Product productB=Factory.createProduct("B");
productB.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");
}
}
四、工厂方法模式
📢意图要背
工厂方法代码实现如下:
/**
* @author :CaiCai
* @date : 2023/4/26 11:54
*/
public class FactoryMethods {
public static void main(String[] args) {
Factory factoryA=new FactoryA();
Product productA=factoryA.createProduct();
productA.info();
Factory factoryB=new FactoryB();
Product productB=factoryB.createProduct();
productB.info();
}
}
//class Factory
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();
}
}
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");
}
}
五、抽象工厂模式
抽象工厂模式代码如下:
/**
* @author :CaiCai
* @date : 2023/4/26 11:54
*/
public class AbstractFactory {
public static void main(String[] args) {
Factory factory1=new Factory1();
ProductA productA=factory1.createProductA();
productA.info();
Factory factory2=new Factory2();
ProductB productB=factory2.createProductB();
productB.info();
}
}
//class Factory
interface Factory{
public ProductA createProductA();
public ProductB createProductB();
}
class Factory1 implements Factory{
@Override
public ProductA createProductA() {
return new ProductA1();
}
@Override
public ProductB createProductB() {
return new ProductB1();
}
}
class Factory2 implements Factory{
@Override
public ProductA createProductA() {
return new ProductA2();
}
@Override
public ProductB createProductB() {
return new ProductB2();
}
}
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");
}
}
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");
}
}
2
3
六、生成器模式
生成器模式代码如下:
import java.util.ArrayList;
import java.util.List;
/**
* @author :CaiCai
* @date : 2023/4/26 13:49
*
*/public class Main {
public static void main(String[] args) {
Director director=new Director();
Builder builder1=new Builder1();
director.Construct(builder1);
Product product1=builder1.getResult();
product1.show();
Builder builder2=new Builder2();
director.Construct(builder2);
Product product2=builder2.getResult();
product2.show();
}
}
class Director{
public void Construct(Builder builder){
builder.BuildPart();
}
}
abstract class Builder{
public abstract void BuildPart();
public abstract Product getResult();
}
class Builder1 extends Builder{
Product product=new Product();
@Override
public void BuildPart(){
product.Add("A");
product.Add("B");
product.Add("C");
product.Add("D");
}
@Override
public Product getResult(){
return product;
}
}
class Builder2 extends Builder{
Product product=new Product();
@Override
public void BuildPart(){
product.Add("A");
product.Add("B");
product.Add("C");
}
@Override
public Product getResult(){
return product;
}
}
class Product{
List<String> parts=new ArrayList<String>();
public void Add(String part){
parts.add(part);
}
public void show(){
System.out.println("产品的组成:");
for(String s : parts)
System.out.print(s+"");
System.out.print("\n");
}
}
4
5
6
七、原型模式
原型模式代码实现如下:
public class Main {
public static void main(String[] args) {
Product product1=new Product(2023,4.26);
System.out.println(product1.getId()+" "+product1.getPrice());
Product product2=(Product)product1.Clone();
System.out.println(product2.getId()+" "+product2.getPrice());
}
}
interface Prototype{
public Object Clone();
}
class Product implements Prototype{
private int id;
private double price;
public Product(){}
public Product(int id,double price){
this.id=id;
this.price=price;
}
public int getId(){
return id;
}
public double getPrice(){
return price;
}
@Override
public Object Clone(){
Product object=new Product();
object.id=this.id;
object.price=this.price;
return object;
}
}
八、单例模式
单例模式代码如下:
public class SingletonPattern {
public static void main(String[] args) {
Singleton singleton1=Singleton.getInstance();
Singleton singleton2=Singleton.getInstance();
Singleton singleton3=Singleton.getInstance();
System.out.println(singleton1.getNumber()+" "+singleton2.getNumber()+" "+singleton3.getNumber());
singleton1.setNumber(2024);
System.out.println(singleton1.getNumber()+" "+singleton2.getNumber()+" "+singleton3.getNumber());
}
}
class Singleton{
private int number=2023;
public void setNumber(int number){
this.number=number;
}
public int getNumber(){
return number;
}
private static Singleton instance=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
7
8
9
结构型设计模式(7种)
结构型速记:桥代理组装适配器,享元回家装饰外观
(乔丹代理了组合(两台)适配器),享元(人名)买回家装饰外观。
九、适配器模式
public class AdaptPattern {
public static void main(String[] args) {
Target target=new Adapter();
target.Request();
}
}
class Target{
public void Request(){
System.out.println("普通请求");
}
}
class Adapter extends Target{
private Adapt adapt=new Adapt();
@Override
public void Request(){
adapt.SpecificRequest();
}
}
class Adapt{
public void SpecificRequest(){
System.out.println("特殊请求");
}
}
10
十、桥接模式
桥接模式代码实现如下:
public class BridgePattern {
public static void main(String[] args) {
Product productA1=new ProductA();
Product productA2=new ProductA();
Color red=new Red();
productA1.setName("产品A1");
productA1.setColor(red);
productA1.Operation();
Blue blue=new Blue();
productA2.setName("产品A2");
productA2.setColor(blue);
productA2.Operation();
}
}
abstract class Product {
private String name;
protected Color color;
public void setName(String name) {
this.name = name;
}
public String getName() {
return 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+":蓝色");
}
}
11
12
13
十一、组合模式
组合模式添加和删除代码实现:
import java.util.ArrayList;
import java.util.List;
public class CompositePattern {
public static void main(String[] args) {
AbstractFile root=new Folder("root");
AbstractFile folderA=new Folder("folderA");
AbstractFile fileB=new File("fileB");
System.out.println(root.Add(folderA));
System.out.println(root.Add(fileB));
System.out.println(root.Remove(fileB));
System.out.println(root.Remove(fileB));
}
}
abstract class AbstractFile{
protected String name;
public void printName(){
System.out.println(name);
}
public abstract boolean Add(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;
}
}
14
15
16
十二、装饰器模式
装饰器模式代码实现:
public class DecoratePattern {
public static void main(String[] args) {
Person zhangsan=new Student("张三");
zhangsan.Operation();
System.out.println("\n=======我是分割线=======");
// Decorator decoratorA=new DecoratorA(zhangsan);
// decoratorA.Operation();
zhangsan=new DecoratorA(zhangsan);
zhangsan.Operation();
}
}
abstract class Decorator extends Person{
protected Person person;
}
class DecoratorA extends Decorator{
public DecoratorA(Person person){
this.person=person;
}
@Override
public void Operation(){//职责
person.Operation();//原本的职责
System.out.print("写作业");
}
}
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.print(name+"的职责:学习");
}
}
17
十三、外观模式
外观模式代码实现:
import javax.security.auth.Subject;
public class FacadePattern {
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("执行子系统一的功能");
}
}
class SubSystemTwo{
public void methodTwo(){
System.out.println("执行子系统二的功能");
}
}
class SubSystemThree{
public void methodThree(){
System.out.println("执行子系统三的功能");
}
}
18
19
十四、享元模式
20
十五、代理模式
代理模式代码实现:
public class ProxyPattern {
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("付钱");
}
}
21
行为型设计模式(11种)
十六、责任链模式
代码实现:
十七、命令模式
22
23
十八、解释器模式
十九、迭代器模式
二十、中介者模式
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("2023年5月27软考");
}
}
abstract class Colleague{
protected Mediator mediator;
}
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);
}
}
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;
}
public void sendMessage(String message,Colleague colleague){
if(colleague==colleague1){
//让同事2收到消息
colleague2.Notify(message);
}else {
//让同事1收到消息
colleague1.Notify(message);
}
}
}
24
二十一、备忘录模式
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("427");
Memento backup1=originator.createMemento();
caretaker.addMemento(backup1);
originator.setState("428");
Memento backup2=originator.createMemento();
caretaker.addMemento(backup2);
originator.setState("429");
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(Memento memento:mementoList){
System.out.println("第" + cnt +" 次备份,状态为:"+memento.getState());
cnt++;
}
}
}
二十一、观察者模式
25
26
27
28
29
30
31
二十二、状态模式
代码实现:
public class StatePattern {
public static void main(String[] args) {
Context context=new Context();
System.out.println(context.getState());
context.Request();//2
context.Request();//1
context.Request();//0
System.out.println(context.getState());
context.Request();//无货
}
}
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 getState(State state){
this.state=state;
}
public void Request(){//购买一瓶饮料
state.Handle(this);
}
public void setState(StateA stateA) {
}
public void SetState(StateB stateB) {
}
}
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());
}
}
}
32
33
44-47 B A D C
二十三、策略模式
34
35
36
二十四、模板方法模式
二十五、访问者模式
代码实现:
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("===============");
Visitor2 visitor2=new Visitor2();
System.out.println("访问者2访问记录");
structure.Accept(visitor2);
}
}
interface Visitor{
public void visitStudent(Student student);
public void visitTeacher(Teacher teacher);
}
class Visitor1 implements Visitor{
@Override
public void visitStudent(Student student){
System.out.println("访问者1访问学生"+student.name);
}
@Override
public void visitTeacher(Teacher teacher){
System.out.println("访问者1访问老师"+teacher.name);
}
}
class Visitor2 implements Visitor{
@Override
public void visitStudent(Student student){
System.out.println("访问者2访问学生"+student.name);
}
@Override
public void visitTeacher(Teacher teacher){
System.out.println("访问者2访问老师"+teacher.name);
}
}
class PersonStructure{
private List<Person> personList=new ArrayList<Person>();
public PersonStructure(){
personList.add(new Student("张三"));
personList.add(new Student("李四"));
personList.add(new Student("王五"));
personList.add(new Student("李老师"));
personList.add(new Student("陈老师"));
personList.add(new Student("刘老师"));
}
public void Accept(Visitor visitor){
for(Person person:personList){
person.Accept(visitor);
}
}
}
abstract class Person{
public String name;
public abstract void Accept(Visitor visitor);
}
class Student extends Person{
public Student(String name){
this.name=name;
}
@Override
public void Accept(Visitor visitor){
visitor.visitStudent(this);
}
}
class Teacher extends Person{
public Teacher(String name){
this.name=name;
}
@Override
public void Accept(Visitor visitor){
visitor.visitTeacher(this);
}
}
37
Accept只在访问者模式出现
38
二十六、设计模式总和
39
40
41
结构型:适配桥想组装外带
42
43
44
45
文章来源:https://www.toymoban.com/news/detail-471149.html
46
文章来源地址https://www.toymoban.com/news/detail-471149.html
本章完结撒花👏👏👏👏
到了这里,关于【中级软件设计师】—(针对上午题)二十三种设计模式(三十九)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!