第十二周总结

Java 学习第十二周总结
一、学习概述
本周学习内容涵盖 WebAssembly 性能优化、Three.js 3D 图形渲染、TypeScript 高级特性、React 框架进阶以及 Android 应用开发。通过实践 WebAssembly 与 Rust 的集成,掌握高性能计算场景的前端实现;深入学习 Three.js 实现 3D 交互效果;探索 TypeScript 泛型与高级类型提升代码健壮性;在 React 中实践 Hooks 高级用法与性能优化;同时开启 Android 开发之旅,掌握 Android Studio 环境配置与应用开发基础。
二、WebAssembly 与 WebGL 实践

  1. 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 高级特性

  1. 泛型编程
    泛型函数与接口

// 泛型函数
function identity(arg: T): T {
return arg;
}
// 泛型接口
interface GenericInterface {
value: T;
getValue(): T;
}
class GenericClass implements GenericInterface {
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 高级主题与最佳实践

  1. 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 ( 
    <div> 
        <p>计数: {count}</p> 
        <p>双倍计数: {doubleCount}</p> 
        <button onClick={increment}>+1</button> 
        <button onClick={decrement}>-1</button> 
    </div> 
); 

}
2. 性能优化实践
React.memo 与 useMemo

// 昂贵组件优化
const ExpensiveComponent = React.memo(({ data }) => {
console.log("渲染昂贵组件");
return

{data}
;
});
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 ( 
    <div> 
        <p>计数: {count}</p> 
        <button onClick={() => setCount(count + 1)}>+1</button> 
        <p>文本: {text}</p> 
        <input value={text} onChange={(e) => setText(e.target.value)} /> 
        <p>计算值: {memoizedValue}</p> 
        <ExpensiveComponent data={memoizedValue} /> 
    </div> 
); 

}
五、Android 应用开发基础

  1. 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">

<TextView 
    android:id="@+id/textView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello, Android!" 
    android:textSize="24sp" 
    app:layout_constraintTop_toTopOf="parent" 
    app:layout_constraintStart_toStartOf="parent" 
    app:layout_constraintEnd_toEndOf="parent" 
    app:layout_constraintTop_margin="80dp"/> 
 
<Button 
    android:id="@+id/button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="点击我" 
    app:layout_constraintTop_toBottomOf="@+id/textView" 
    app:layout_constraintStart_toStartOf="parent" 
    app:layout_constraintEnd_toEndOf="parent" 
    app:layout_constraintTop_margin="40dp"/> 

</androidx.constraintlayout.widget.ConstraintLayout>
Activity 生命周期与事件处理

public class MainActivity extends AppCompatActivity {
private TextView textView;
private Button button;

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
     
    textView = findViewById(R.id.textView); 
    button = findViewById(R.id.button); 
     
    button.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
            // 显示Toast提示 
            Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show(); 
            // 更新文本内容 
            textView.setText("按钮已点击!"); 
        } 
    }); 
} 
 
@Override 
protected void onStart() { 
    super.onStart(); 
    Log.d("MainActivity", "onStart: 活动开始可见"); 
} 
 
@Override 
protected void onResume() { 
    super.onResume(); 
    Log.d("MainActivity", "onResume: 活动获取焦点"); 
} 

}
2. 性能优化实践
布局优化与 ViewStub

<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">

<TextView 
    android:id="@+id/mainText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="主界面内容" 
    app:layout_constraintTop_toTopOf="parent" 
    app:layout_constraintStart_toStartOf="parent"/> 
 
<ViewStub 
    android:id="@+id/advancedStub" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="80dp" 
    app:layout_constraintTop_toBottomOf="@+id/mainText" 
    app:layout_constraintStart_toStartOf="parent" 
    app:layout="@layout/advanced_layout"/> 

</androidx.constraintlayout.widget.ConstraintLayout>

// 代码中动态加载ViewStub
public class OptimizedActivity extends AppCompatActivity {
private ViewStub advancedStub;

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_optimized); 
     
    advancedStub = findViewById(R.id.advancedStub); 
     
    findViewById(R.id.loadButton).setOnClickListener(v -> { 
        // 加载ViewStub布局 
        if (advancedStub != null) { 
            advancedStub.inflate(); 
        } 
    }); 
} 

}
六、本周学习总结与反思

  1. 学习成果
  2. 掌握 WebAssembly 与 Rust 的集成开发,能实现高性能计算模块
  3. 熟练使用 Three.js 构建 3D 场景,实现交互效果
  4. 精通 TypeScript 泛型与高级类型,提升代码类型安全性
  5. 掌握 React Hooks 高级用法,能封装自定义 Hook 与状态管理
  6. 完成 Android 开发环境搭建,掌握基础布局与 Activity 开发
  7. 理解性能优化原理,能应用 React.memo 与 ViewStub 提升性能
  8. 存在问题
  9. WebAssembly 的内存管理与复杂数据结构传递经验不足
  10. Three.js 的高级材质与光照效果调节不够熟练
  11. TypeScript 泛型约束与条件类型的复杂场景应用欠缺
  12. Android 布局性能优化的深入实践较少
  13. 改进方向
  14. 深入学习 WebAssembly 的内存管理与二进制接口
  15. 实践 Three.js 的纹理映射与 3D 模型加载
  16. 通过复杂项目练习 TypeScript 高级类型操作
  17. 学习 Android 的布局性能分析工具与优化策略
  18. 下周计划
  19. 学习 WebAssembly 与 JavaScript 的复杂数据交互
  20. 深入研究 Three.js 的 3D 模型动画与物理效果
  21. 实践 TypeScript 在大型项目中的类型建模
  22. 学习 Android 的网络请求与数据存储
  23. 阅读《React 性能优化指南》相关章节
posted @ 2025-06-15 21:11  执笔诉相思  阅读(8)  评论(0)    收藏  举报