代码实现
tree
entity/Product.h/cpp
entity/Factory.h/cpp
main.cpp
// Product.h
#ifndef UNTITLED3_PRODUCT_H
#define UNTITLED3_PRODUCT_H
class Product {
public:
virtual ~Product() = 0;
protected:
Product();
};
class AProduct:public Product{
public:
~AProduct();
AProduct();
};
#endif //UNTITLED3_PRODUCT_H
// Product.cpp
#include "Product.h"
Product::~Product() noexcept {}
Product::Product() {}
AProduct::AProduct() {}
AProduct::~AProduct() noexcept {}
// Factory.h
//
// Created by zz on 29/4/23.
//
#ifndef UNTITLED3_FACTORY_H
#define UNTITLED3_FACTORY_H
#include "Product.h"
class Product;
class Factory {
public:
virtual ~Factory() = 0;
virtual Product* createProduct()= 0;
protected:
Factory();
};
class AFactory:public Factory{
public:
AFactory();
~AFactory();
Product* createProduct();
};
#endif //UNTITLED3_FACTORY_H
// Factory.cpp
//
// Created by zz on 29/4/23.
//
#include "Factory.h"
Factory::~Factory() noexcept {}
Factory::Factory(){}
AFactory::~AFactory() noexcept {}
AFactory::AFactory(){}
Product* AFactory::createProduct() {
return new AProduct();
}
//main.cpp
#include <iostream>
#include "entity/Factory.h"
#include "entity/Product.h"
using namespace std;
int main() {
Factory* af = new AFactory();
Product* aP = af->createProduct();
return 0;
}
# CMakeLists.txt
cmake_minimum_required(VERSION 3.25)
project(untitled3)
set(CMAKE_CXX_STANDARD 17)
add_executable(untitled3 main.cpp entity/Factory.cpp entity/Factory.h entity/Product.cpp entity/Product.h )
真正说明!!!!(notice here)
- 文件结构
F...(F(not create object),RealF(create object))
P...(P(not create object),RealP(not create object))
- 要点解释
- 两个文件的F,P指一个
不真正干事的类
,真正干事或者真正产品在RealF,RealP
…(如果还有其他真正F,P) 所有的F,P...类的默认无参构造函数都设置为保护成员
- 核心在工厂F文件,F工厂有两个虚函数,一个
虚析构函数保证子类能调用自身的析构
,一个虚创建产品方法
,在真正工厂中实现这个创建产品方法(返回真正产品指针) - 怎么使用: 视F,P为父类,父类工厂指针指向真正工厂类,产品父类指针指向
真正工厂创建的真正产品
延伸到:抽象工厂模式
有用的解释(notice)
- 对于不干事或者不是真正产品的类,必须是提供父类指针,一般先设置
保护默认构造
和公有虚析构
,而真正的F,P是要把析构和无参构造设置为公有
- 对于F工厂来说,父(抽象工厂)是定义
虚创建SomeP的函数
(SomeP真正产品可能有多个)(虚函数),那么这个函数是要在真正工厂中实现,并且明确返回的是某某接口类P(就是抽象的产品 )指针
- AF管理由ABSPA派生的任意子产品,不像工厂模式那样一个真正工厂创建一种对应的真正产品,这里的AF能力更强,能创建多个相似的产品
设计模式的使用场景
- 有开发经验才进一步学习设计模式
- 不要滥用设计模式,只有业务特别复杂不好处理耦合时才考虑设计模式,设计模式只是方案,不一定是最好的,不要过早优化
- 创建型:创建类
结构型:类之间的关系
行为型:类的通讯 - 过时的设计模式和语言内置的设计模式
熟记使用场景
来自itbaima.net(自己看吧,我就不搬运代码了)
设计原则
创建型
工厂方法
public abstract class Fruit{
private final String name;
public Fruit(String name){
this.name = name;
}
@Override
public String toString(){
return name + "@" + hashCode();
}
}
---
public class Apple extends Fruit{
public Apple(){
super("苹果");
}
}
---
public class Orange extends Fruit{
public Orange(){
super("橘子");
}
}
---
---
public class FruitFactory{
public static Fruit getFruit(String type){
switch (type){
case "苹果":
return new Apple();
case "橘子":
return new Orange();
default:
return null;
}
}
}
---
public class Main{
public static void main(String[] args){
Fruit apple = FruitFactory.getFruit("苹果");
System.out.println(apple);
}
}
简单工厂加强工厂方法模式
public abstract class FruitFactory<T extends Fruit>{
public abstract T getFruit();
}
---
public class AppleFactory extends FruitFactory<Apple>{
@Override
public Apple getFruit(){
return new Apple();
}
}
---
public class OrangeFactory extends FruitFactory<Orange>{
@Override
public Orange getFruit(){
return new Orange();
}
}
---
public class Main{
private static void genFruit(Supplier<Fruit> supplier){
System.out.println(supplier.get() + "生成了");
}
public static void main(String[] args){
genFruit(new AppleFactory()::genFruit);
}
}
抽象工厂模式(不怎么用)
public class Router{}
---
public class Table{}
---
public class Phone{}
---
public abstract class Abstractfactory{
public abstract Phone getPhone();
public abstract Table getTable();
public abstract Router getRouter();
}
建造者模式
public class Student{
int id;
int age;
int grade;
String name;
String college;
String profession;
List<String> awards;
public Student(int id, int age, int grade, String name,String college, String profession, List<String> awards){
this.id = id;
this.name = name;
// this....
}
}
---
// good
public class Student{
public Student(int id, int age, int grade, String name,String college, String profession, List<String> awards){
//...
}
public static StudentBuilder builder(){
return new StudentBuilder();
}
public static class StudentBuilder{
int id;
int age;
int grade;
String name;
String college;
String profession;
List<String> awards;
public StudentBuilder id(int id){
this.id = id;
return this;
}
// 对每一个字段都应用上面类似的方法
public Student build(){
return new Student(id,age,/*...*/);
}
}
}
---
public static void main(String[] args){
Student student = Student.builder()
.id(1)
.age(10)
//...
.build();
}
单例模式
// 饿汉式
public class Singleton{
private final static Singleton Instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return Instance;
}
}
---
public class Main{
public static void main(String[] args){
Singleton onlyme= Singleton.getInstance();
}
}
---
// 懒汉式
public class Singleton{
private static Singleton Instance;
private Singleton(){}
public static Singleton getInstance(){
if (Instance == null){
Instance = new Singleton();
}
return Instance;
}
}
// 还有多线程的方式,加sync,加vol?...
原型模式(其实就是拷贝原有的实例属性值,再创建新的对象)
// 未实现深拷贝,对象地址相同
public class Student implements Cloneable{
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
---
public class Main{
public static void main(String[] args) throws CloneNotSupportedException {
Student s1 = new Student();
Student s2 = (Student)s1.clone();
System.out.println(s1);
System.out.println(s2);
}
}
---
// 实现深拷贝
public class Student implements Cloneable{
String name;
public Student(String name){
this.name = name;
}
public String getName(){
return this.name;
}
@Override
public Object clone() throws CloneNotSupportedException{
Student student = (Student)super.clone();
student.name = new String(name);
return student;// 深拷贝字段
}
}
---
public class Main{
public static void main(String[] args) {
Student ss = new Student("xiao");
Student sss = (Student)ss.clone();
System.out.println(ss.getName() == sss.getName());// false
}
}
结构型
类/对象适配器模式
思想:220v 转 5v, 成功给手机充电
// 类适配器
public class HuaWeiSupplier{
public String doSupply(){
return "Huawei works";
}
}
---
public interface Target{
String supply();
}
---
public class HuaWeiAdapter extends HuaWeiSupplier implements Target{
@Override
public String supply(){
return super.doSupply();
}
}
---
public class Main{
public static void forTarget(Target target){
System.out.println(target.supply());
}
public static void main(String[] args) {
HuaWeiAdapter adapter = new HuaWeiAdapter();
forTarget(adapter);
}
}
---
// 对象适配器
public class HuaWeiAdapter implements Target{
HuaWeiSupplier supplier;
public HuaWeiAdapter(HuaWeiSupplier supplier){
this.supplier = supplier;
}
@Override
public String supply(){
return supplier.doSupply();
}
}
桥接模式
为同一事物抽象其相同属性
// 属性类
public interface Size{
String getSize();
}
---
public interface Tea{
String getType();
}
---
public abstract class AbstractTea{
protected Size size;
protected AbstractTea(Size size){
this.size = size;
}
public abstract String getType();
}
---
public abstract class RefineAbstractTea extends AbstractTea{
protected RefineAbstractTea(Size size){
super(size);
}
public String getSize(){
return size.getSize();
}
}
---
// 相同属性的扩展
public class Large implements Size{
@Override
public String getSize(){
return "大杯";
}
}
---
public class KissTea extends RefineAbstractTea{
protected KissTea(Size size){
super(size);
}
@Override
public String getType(){
return "芋泥啵啵奶茶";
}
}
---
// 测试
public class Main{
public static void main(String[] args) {
KissTea tea = new KissTea(new Large());
System.out.println(tea.getType());
System.out.println(tea.getSize());
}
}
组合模式
组合模式实际上就是将多个组件进行组合,让用户可以对它们进行一致性处理
public abstract class Component{
public abstract void addComponent(Component comp);
public abstract void removeComponent(Component comp);
public abstract Component getChild(int index);
public abstract void test();
}
---
public class Dir extends Component{
List<Component> childs = new ArrayList<>();
@Override
public void addComponent(Component comp){
childs.add(comp);
}
@Override
public void removeComponent(Component comp){
childs.remove(comp);
}
@Override
public Component getChild(int index){
return childs.get(index);
}
@Override
public void test(){
childs.forEach(Component::test);
}
}
---
public class File extends Component{
@Override
public void addComponent(Component comp){
throw new UnsupportedOperationException();// 不支持
}
@Override
public void removeComponent(Component comp){
throw new UnsupportedOperationException();
}
@Override
public Component getChild(int index){
throw new UnsupportedOperationException();
}
@Override
public void test(){
System.out.println("文件名称修改成功"+this);
}
}
---
public class Main{
public static void main(String[] args) {
Dir outer = new Dir();
Dir inner = new Dir();
outer.addComponent(inner);
outer.addComponent(new File());
outer.addComponent(new File());
inner.addComponent(new File());
inner.addComponent(new File());
outer.test();
}
}
装饰模式
为对象添加功能,但并不改变对象本身的结构
public abstract class Base{
public abstract void test();
}
---
public class BaseImpl extends Base{
@Override
public void test(){
println("我是业务方法");
}
}
---
public class Decorator extends Base{
protected Base base;
public Decorator(Base base){
this.base = base;
}
@Override
public void test(){
base.test();
}
}
---
public class DecoratorImpl extends Decorator{
public DecoratorImpl(Base base){
super(base);
}
@Override
public void test(){
println("before test()");
super.test();
println("after test()");
}
}
---
public static void main(String[] args) {
Base base = new BaseImpl();
Decorator decorator = new DecoratorImpl(base);
Decorator outer = new DecoratorImpl(decorator);
decorator.test();
outer.test();
}
代理模式
直接访问对象难时,代理对象间接访问
public abstract class Subject{
public abstract void test();
}
---
public class SubjectImpl extends Subject{
@Override
public void test(){
println("test called");
}
}
---
// 代理类
public class Proxy extends Subject{
Subject target;
public Proxy(Subject sub){
this.target = sub;
}
@Override
public void test(){
println("代理前");
target.test(); // Subject注入组合到这个类
println("代理后");
}
}
---
public static void main(String[] args) {
SubjectImpl sub = new SubjectImpl();
Proxy pro = new Proxy(sub);
pro.test();
}
外观模式
类之间应该少交互避免太耦合
public class SystemA{
public void testA(){
println("A子系统 test");
}
}
---
public class SystemB{
public void testB(){
println("B子系统 test");
}
}
---
public class SystemC{
public void testC(){
println("C子系统 test");
}
}
---
// 门面整合子系统
public class Facade{
SystemA a = new SystemA();
SystemB b = new SystemB();
SystemC c = new SystemC();
public void doSysAll(){
a.testA();
b.testB();
c.testC();
}
}
---
public static void main(String[] args) {
Facede f = new Facade();
f.doSysAll();
}
享元模式
优化内存,共享已出现的数据
public class DBUtil{
public void selectDb(){
println("选择数据库");
}
}
---
public class DBUtilFactory{
private static final DBUtil Util = new DBUtil();
// 获取享元对象
public static DBUtil getFlyweight(){
return Util;
}
}
---
// 使用享元对象
public class UserService{
public void service(){
DBUtil util = DBUtilFactory.getFlyweight();
util.selectDb();
}
}
---
// String 的内部享元实现
public static void main(String[] args) {
String s1= "abcd";
String s2= "abcd";
String s3 = "ab" + "cd";
println(s1==s2);
println(s2==s3);
}