范式(Paradigm) 在编程中指一套组织代码的思维方式、原则和模式,它定义了程序员如何看待程序结构和解决问题的视角。
| 范式 | 核心思想 | 代码组织方式 | 状态管理 | 典型场景 | 代表语言/技术 |
|---|---|---|---|---|---|
| 面向过程 | 算法步骤序列 | 函数调用流程 | 可变状态 | 系统程序、脚本 | C, Pascal, BASIC |
| 面向对象 | 交互对象集合 | 类与对象关系 | 对象内部状态 | GUI、企业应用 | Java, C#, Python |
| 函数式 | 数学函数计算 | 函数组合管道 | 不可变状态 | 数据处理、并发 | Haskell, Lisp, JS FP |
| 逻辑式 | 逻辑规则推理 | 事实与规则 | 逻辑状态 | 专家系统、AI | Prolog, Datalog |
| 声明式 | 描述结果 | 规则/约束声明 | 无显式状态 | 查询、配置 | SQL, HTML, CSS |
| 响应式 | 数据流响应 | 观察者/流操作 | 流状态 | 实时系统、UI | RxJS, ReactiveX |
| 并发式 | 并行执行 | 线程/进程通信 | 共享/消息状态 | 高并发系统 Erlang, Go, Rust |
核心理念:程序是一系列指令的集合
特点:
// C语言典型示例
#include <stdio.h>
// 数据结构与操作分离
struct Rectangle {
float width;
float height;
};
// 操作数据的函数
float calculate_area(struct Rectangle rect) {
return rect.width * rect.height;
}
void scale_rectangle(struct Rectangle *rect, float factor) {
rect->width *= factor;
rect->height *= factor;
}
int main() {
struct Rectangle my_rect = {5.0, 3.0};
printf("Area: %.2f\n", calculate_area(my_rect));
scale_rectangle(&my_rect, 1.5);
return 0;
}
核心理念:程序是相互作用的对象网络
四大支柱:
// Java典型示例 - 封装、继承、多态
abstract class PaymentMethod {
protected double amount;
public PaymentMethod(double amount) {
this.amount = amount;
}
// 抽象方法 - 多态基础
public abstract boolean processPayment();
// 模板方法模式
public final void execute() {
if(validate()) {
processPayment();
sendReceipt();
}
}
protected boolean validate() {
return amount > 0;
}
private void sendReceipt() {
System.out.println("Receipt sent for: $" + amount);
}
}
// 继承实现
class CreditCardPayment extends PaymentMethod {
private String cardNumber;
public CreditCardPayment(double amount, String cardNumber) {
super(amount);
this.cardNumber = cardNumber;
}
@Override
public boolean processPayment() {
System.out.println("Processing credit card: " + cardNumber);
return true;
}
@Override
protected boolean validate() {
return super.validate() && cardNumber != null && cardNumber.length() == 16;
}
}
// 使用
PaymentMethod payment = new CreditCardPayment(99.99, "1234567812345678");
payment.execute(); // 多态调用
核心理念:程序是纯函数的组合
核心概念:
// 现代JS函数式实践
const fp = {
// 柯里化
curry:
fn =>
(...args) =>
args.length >= fn.length ? fn(...args) : fp.curry(fn.bind(null, ...args)),
// 函数组合
compose:
(...fns) =>
x =>
fns.reduceRight((acc, fn) => fn(acc), x),
// Maybe Monad处理空值
Maybe: value => ({
map: fn => (value == null ? fp.Maybe(null) : fp.Maybe(fn(value))),
flatMap: fn => (value == null ? fp.Maybe(null) : fn(value)),
getOrElse: defaultValue => value ?? defaultValue,
}),
};
// 使用
const safeParseJSON = str =>
fp
.Maybe(str)
.map(s => JSON.parse(s))
.getOrElse({});
const processUser = fp.compose(user => user?.name ?? "Anonymous", safeParseJSON);
核心理念:程序是逻辑规则的事实库
特点:
% Prolog示例 - 家族关系推理
% 事实数据库
parent(john, mary).
parent(john, tom).
parent(mary, ann).
parent(mary, bob).
parent(tom, lisa).
female(mary).
female(ann).
female(lisa).
male(john).
male(tom).
male(bob).
% 规则定义
mother(X, Y) :- parent(X, Y), female(X).
father(X, Y) :- parent(X, Y), male(X).
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
sibling(X, Y) :- parent(Z, X), parent(Z, Y), X \= Y.
% 查询系统自动推理
% ?- mother(mary, ann). → true
% ?- grandparent(john, Who). → Who = ann; Who = bob; Who = lisa
核心理念:描述做什么,而非怎么做
-- SQL是典型的声明式语言
WITH monthly_sales AS (
SELECT
DATE_TRUNC('month', order_date) AS month,
product_id,
SUM(quantity * price) AS revenue,
RANK() OVER (PARTITION BY DATE_TRUNC('month', order_date)
ORDER BY SUM(quantity * price) DESC) AS rank
FROM orders
JOIN products USING (product_id)
WHERE order_date >= '2024-01-01'
GROUP BY 1, 2
)
SELECT
month,
product_id,
revenue
FROM monthly_sales
WHERE rank <= 3 -- 每月Top 3产品
ORDER BY month DESC, rank;
# Kubernetes配置(声明期望状态)
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3 # 声明需要3个副本
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: app
image: my-app:v1.0
ports:
- containerPort: 8080
核心理念:程序是异步数据流的传播与变换
核心概念:
// RxJS示例 - 处理复杂异步流
import { fromEvent, merge, of } from "rxjs";
import { map, filter, debounceTime, switchMap, catchError } from "rxjs/operators";
// 创建搜索输入流
const searchInput = document.getElementById("search");
const search$ = fromEvent(searchInput, "input").pipe(
map(event => (event.target as HTMLInputElement).value),
filter(term => term.length > 2),
debounceTime(300), // 防抖
distinctUntilChanged(), // 去重
switchMap(
(
term // 切换到新请求,取消旧的
) =>
ajax.getJSON(`/api/search?q=${term}`).pipe(
catchError(() => of([])) // 错误处理
)
)
);
// 组合多个流
const filter$ = fromEvent(filterSelect, "change");
const sort$ = fromEvent(sortSelect, "change");
const results$ = merge(
search$,
filter$.pipe(switchMap(() => search$)),
sort$.pipe(switchMap(() => search$))
).pipe(
shareReplay(1) // 共享订阅
);
// 订阅结果
results$.subscribe(results => {
renderResults(results);
});
核心理念:程序是并行执行的协作单元
// Go - CSP模型(基于通道)
func worker(id int, jobs <-chan int, results chan<- int) {
for job := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, job)
results <- job * 2
}
}
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// 启动3个worker
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// 发送工作
for j := 1; j <= 9; j++ {
jobs <- j
}
close(jobs)
// 收集结果
for r := 1; r <= 9; r++ {
<-results
}
}
// Rust - 基于所有权的并发
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
现代趋势是融合:
// React组件:声明式UI + 函数式逻辑 + 响应式状态
const Dashboard = () => {
// 函数式:Hooks(useState返回元组)
const [data, setData] = useState([]);
const [filter, setFilter] = useState("all");
// 响应式:Effect处理副作用
useEffect(() => {
const subscription = dataStream$
.pipe(
debounceTime(100),
filter(newData => newData.type === filter)
)
.subscribe(newData => {
setData(prev => [...prev, newData]); // 不可变更新
});
return () => subscription.unsubscribe(); // 清理
}, [filter]);
// 面向对象:组件实例化
const chart = new Chart(config);
// 声明式渲染
return (
<div className="dashboard">
{/* 函数式数据转换 */}
{data
.filter(item => item.active)
.map(item => (
<Card
key={item.id}
item={item} // 属性传递
onUpdate={handleUpdate} // 方法传递
/>
))}
</div>
);
};
# 声明式配置
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: order-service
spec:
template:
spec:
containers:
- image: order-service:latest
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
# 函数式业务逻辑
const processOrder = R.pipe(
validateOrder, // 验证
applyDiscounts, // 计算
checkInventory, // 检查
createPaymentIntent,// 支付
R.tap(logOrder) // 日志(副作用隔离)
);
# 响应式通信
orderEvents$.pipe(
groupBy(order => order.customerId),
mergeMap(group$ =>
group$.pipe(
bufferTime(5000), // 5秒窗口
filter(orders => orders.length > 0),
map(orders => createBatch(orders))
)
)
).subscribe(sendToWarehouse);
初学者:面向过程 → 面向对象 → 函数式
进阶者:响应式 → 声明式 → 并发模型
专家级:逻辑编程 → 领域特定范式