第十二周总结
Java 学习第十二周总结
一、学习概述
本周学习内容涵盖 WebAssembly 性能优化、Three.js 3D 图形渲染、TypeScript 高级特性、React 框架进阶以及 Android 应用开发。通过实践 WebAssembly 与 Rust 的集成,掌握高性能计算场景的前端实现;深入学习 Three.js 实现 3D 交互效果;探索 TypeScript 泛型与高级类型提升代码健壮性;在 React 中实践 Hooks 高级用法与性能优化;同时开启 Android 开发之旅,掌握 Android Studio 环境配置与应用开发基础。
二、WebAssembly 与 WebGL 实践
- WebAssembly 性能优化
Rust 与 WebAssembly 集成
安装Rust工具链
curl https://sh.rustup.rs -sSf | sh
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
// src/lib.rs
use wasm_bindgen::prelude::;
// 使用wasm_bindgen注解暴露函数到JavaScript
[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
[wasm_bindgen]
pub fn calculate(a: f64, b: f64, op: &str) -> f64 {
match op {
"+" => a + b,
"-" => a - b,
"" => a * b,
"/" => a / b,
_ => 0.0
}
}
编译为WebAssembly
wasm-pack build --target web
JavaScript 调用 WebAssembly
import init, { add, calculate } from './pkg/wasm_module.js';
async function runWasm() {
await init();
console.log('2 + 3 =', add(2, 3));
console.log('5.5 * 2 =', calculate(5.5, 2, '*'));
}
runWasm();
2. Three.js 3D 图形渲染
基础 3D 场景搭建
import * as THREE from 'three';
// 创建场景、相机与渲染器
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建几何体与材质
const geometry = new THREE.BoxGeometry(2, 2, 2);
const material = new THREE.MeshStandardMaterial({
color: 0x00ff00,
metalness: 0.3,
roughness: 0.4
});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 添加光源
const ambientLight = new THREE.AmbientLight(0x404040, 2);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 5, 5);
scene.add(directionalLight);
// 动画循环
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
交互与材质进阶
// 添加鼠标交互
const mouse = new THREE.Vector2();
window.addEventListener('mousemove', (event) => {
mouse.x = event.clientX / window.innerWidth - 0.5;
mouse.y = -(event.clientY / window.innerHeight - 0.5);
});
// 实现鼠标跟踪效果
const onWindowResize = () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
window.addEventListener('resize', onWindowResize);
三、TypeScript 高级特性
- 泛型编程
泛型函数与接口
// 泛型函数
function identity
return arg;
}
// 泛型接口
interface GenericInterface
value: T;
getValue(): T;
}
class GenericClass
constructor(public value: T) {}
getValue(): T { return this.value; }
}
// 使用泛型约束
function getLength<T extends { length: number }>(arg: T): number {
return arg.length;
}
2. 高级类型操作
交叉类型与联合类型
// 交叉类型(合并多个类型)
type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
startDate: Date;
};
type AdminEmployee = Admin & Employee; // 同时具备Admin和Employee的属性
// 联合类型(值可以是多种类型之一)
type ID = string | number;
function printID(id: ID) {
console.log(typeof id === 'string' ? id.toUpperCase() : id);
}
// 类型保护
function isNumber(id: ID): id is number {
return typeof id === 'number';
}
条件类型与映射类型
// 条件类型
type TypeName
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
T extends undefined ? "undefined" :
T extends Function ? "function" : "object";
// 映射类型
type ReadonlyKeys
readonly [K in keyof T]: T[K];
};
type PartialKeys
[K in keyof T]?: T[K];
};
四、React 高级主题与最佳实践
- Hooks 高级用法
useReducer 与 Context 结合
// 主题状态管理
const themeReducer = (state, action) => {
switch (action.type) {
case 'LIGHT': return 'light';
case 'DARK': return 'dark';
default: return state;
}
};
const ThemeContext = React.createContext();
function ThemeProvider({ children }) {
const [theme, dispatch] = React.useReducer(themeReducer, 'light');
return (
<ThemeContext.Provider value={{ theme, dispatch }}>
{children}
</ThemeContext.Provider>
);
}
// 主题按钮组件
function ThemedButton() {
const { theme, dispatch } = React.useContext(ThemeContext);
return (
<button
className={theme}
onClick={() => dispatch({ type: theme === 'light' ? 'DARK' : 'LIGHT' })}
>
切换主题 ({theme})
);
}
// 应用组件
function App() {
return (
);
}
自定义 Hooks 封装
// 计数器Hook
function useCounter(initialValue = 0) {
const [count, setCount] = React.useState(initialValue);
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
// 使用自定义Hook
function CounterApp() {
const { count, increment, decrement } = useCounter(0);
const doubleCount = count * 2;
return (
计数: {count}
双倍计数: {doubleCount}
);
}
2. 性能优化实践
React.memo 与 useMemo
// 昂贵组件优化
const ExpensiveComponent = React.memo(({ data }) => {
console.log("渲染昂贵组件");
return
});
function ParentComponent() {
const [count, setCount] = React.useState(0);
const [text, setText] = React.useState("");
// 仅当count变化时重新计算
const memoizedValue = React.useMemo(() => {
console.log("重新计算值");
return count * 2;
}, [count]);
// 仅当text变化时更新回调
const memoizedCallback = React.useCallback(() => {
console.log("回调函数被调用");
}, [text]);
return (
计数: {count}
<button onClick={() => setCount(count + 1)}>+1
文本: {text}
<input value={text} onChange={(e) => setText(e.target.value)} />
计算值: {memoizedValue}
);
}
五、Android 应用开发基础
- Android Studio 环境配置
项目创建与结构
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
浙公网安备 33010602011771号