前端框架中的设计模式 |青训营

56 阅读1分钟

以下是一些常见的前端设计模式,以及它们的优缺点和使用案例比较分析: 1. MVC 模式(使用 AngularJS):

// Model
class UserModel {
  constructor(name) {
    this.name = name;
  }
}

// View
function renderUser(user) {
  document.getElementById('user-container').innerText = `Hello, ${user.name}!`;
}

// Controller
class UserController {
  constructor(model) {
    this.model = model;
  }

  updateUser(name) {
    this.model.name = name;
    renderUser(this.model);
  }
}

const user = new UserModel('Guest');
const userController = new UserController(user);
userController.updateUser('John');

2. MVVM 模式(使用 Vue.js):

<!-- View (HTML) -->
<div id="app">
  <input v-model="user.name" />
  <p>Hello, {{ user.name }}!</p>
</div>

<!-- JavaScript -->
<script>
const app = new Vue({
  el: '#app',
  data: {
    user: {
      name: 'Guest'
    }
  }
});
</script>

3. 单例模式(使用 Redux store):

// Redux Store (Redux is a state management library for React)
import { createStore } from 'redux';

const initialState = {
  user: {
    name: 'Guest'
  }
};

function userReducer(state = initialState, action) {
  switch (action.type) {
    case 'UPDATE_USER':
      return { ...state, user: { ...state.user, name: action.payload } };
    default:
      return state;
  }
}

const store = createStore(userReducer);

// Usage
store.dispatch({ type: 'UPDATE_USER', payload: 'John' });

4. 观察者模式(使用 DOM 事件):

<button id="btn">Click me</button>

<script>
const button = document.getElementById('btn');

button.addEventListener('click', () => {
  console.log('Button clicked!');
});
</script>

5. 策略模式(表单验证):

class Validator {
  constructor(strategy) {
    this.strategy = strategy;
  }

  validate(value) {
    return this.strategy.validate(value);
  }
}

class RequiredStrategy {
  validate(value) {
    return value.trim() !== '';
  }
}

class MinLengthStrategy {
  constructor(minLength) {
    this.minLength = minLength;
  }

  validate(value) {
    return value.length >= this.minLength;
  }
}

// Usage
const requiredValidator = new Validator(new RequiredStrategy());
const minLengthValidator = new Validator(new MinLengthStrategy(5));

console.log(requiredValidator.validate('')); // false
console.log(minLengthValidator.validate('hello')); // true

6. 装饰者模式(使用 React 高阶组件):

import React from 'react';

// Component
function Button(props) {
  return <button {...props}>Click me</button>;
}

// Higher Order Component (HOC)
function withBorder(Component) {
  return function WithBorder(props) {
    return <div style={{ border: '1px solid black' }}><Component {...props} /></div>;
  };
}

const ButtonWithBorder = withBorder(Button);

// Usage
function App() {
  return (
    <div>
      <ButtonWithBorder onClick={() => console.log('Button clicked!')} />
    </div>
  );
}

这些示例提供了一些关于不同设计模式如何在前端框架中使用的概念。然而,请注意实际代码在真实项目中可能会更加复杂和详细。