State_Pattern

本文深入探讨了状态模式的设计理念,通过具体代码示例展示了如何使用状态模式来管理对象的行为变化,特别是在运行时依赖于其状态的情况下。文章通过定义抽象状态类和具体状态类,配合上下文类,实现了状态之间的无缝切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package state_pattern;

public abstract class State {
    public abstract void Handle(Context context);
}

package state_pattern;

public class ConcreteStateA extends State{
    @Override
    public void Handle(Context context) {//It implements the logic between related state.
        context.setState(new ConcreteStateB());//The current state decide the next state.
    }
}

package state_pattern;

public class ConcreteStateB extends State{
    @Override
    public void Handle(Context context) {
        context.setState(new ConcreteStateA());
    }
}

package state_pattern;

public class Context {
    private State state;
    public Context(State state) {
        this.state = state;
    }
    public State getState() {
        return state;
    }
    public void setState(State state) {
        this.state = state;
        System.out.println("The current state is " + this.state.getClass().getName());
    }
    public void request() {
        state.Handle(this);//The current class object as the parameter communicate
        //with state.The dynamic binding instead of "switch-case".
    }
}

package state_pattern;

public class Main {
    public static void main(String args[]) {
        Context c =  new Context(new ConcreteStateA());       
        c.request();
        c.request();
        c.request();
        c.request();
    }
}
/*
 * The current object's behavior is related to its state during the runtime.
 */

This is a general introduction to the 23 design patterns:
https://blog.youkuaiyun.com/GZHarryAnonymous/article/details/81567214

See more source code:[GZHarryAnonymous](https://github.com/GZHarryAnonymous/Design_Pattern)

# -*- coding: GBK -*- import os import asyncio import aiofiles import re import sqlite3 import json from datetime import datetime source_dest_pairs = [ (r"\\10.10.45.81\Bakpath", r"\\10.10.1.35\iot\639\Datalog\639GE-019"), #(r"\\10.10.55.142\Bakpath", r""), #(r"\\10.10.60.75\Bakpath", r"") ] folder_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$') async def is_csv_empty(file_path): try: async with aiofiles.open(file_path, 'r', encoding='GBK') as csvfile: async for line in csvfile: if line.strip(): return False return True except UnicodeDecodeError: print(f"SKIP: {file_path}") return True def load_state(state_file): if os.path.exists(state_file): with open(state_file, 'r') as f: return json.load(f) return {} def save_state(state_file, state): with open(state_file, 'w') as f: json.dump(state, f) def get_file_mtime(file_path): return os.path.getmtime(file_path) async def process_file(source_path, dest_dir, db_path, state): if await is_csv_empty(source_path): print(f"SKIP: {source_path}") return dest_path = os.path.join(dest_dir, os.path.basename(source_path)) async with aiofiles.open(source_path, 'rb') as src, aiofiles.open(dest_path, 'wb') as dst: await dst.write(await src.read()) print(f"COPY:{source_path} TO {dest_path}") with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cursor.execute("INSERT INTO processed_files (file_path) VALUES (?)", (source_path,)) state[source_path] = get_file_mtime(source_path) async def main(): state_file = 'file_state.json' state = load_state(state_file) tasks = [] for source_dir, dest_dir in source_dest_pairs: if not os.path.exists(source_dir): print(f"!: {source_dir}") continue os.makedirs(dest_dir, exist_ok=True) db_path = os.path.join(dest_dir, 'processed_files.db') with sqlite3.connect(db_path) as conn: cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS processed_files ( file_path TEXT PRIMARY KEY ) ''') cursor.execute("SELECT file_path FROM processed_files") processed_files = {row[0] for row in cursor.fetchall()} for root, dirs, files in os.walk(source_dir): for file in files: if file.endswith('_Alarm.csv'): current_folder = os.path.basename(root) if folder_pattern.match(current_folder): source_path = os.path.join(root, file) if source_path in processed_files: continue file_mtime = get_file_mtime(source_path) file_state = state.get(source_path, None) if file_state is None or file_mtime > file_state: tasks.append(asyncio.create_task(process_file(source_path, dest_dir, db_path, state))) await asyncio.gather(*tasks) save_state(state_file, state) print("ALL SUCCESS") if __name__ == "__main__": asyncio.run(main())
03-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值