关于简单的factorymode

工厂模式是设计模式里面最基础的,也是最经典的,同时也是最常用的一种模式。它的基本思想就是不管你是什么类型,是要你实现了某个接口,我会在工厂里面进行加工统一处理, 通过某个参数得到需要的实现类。下面给出一个简单的工厂模式的代码,仅供参考。
说明:
IC为一个接口,A和B实现了IC接口,通过工厂得到实现类
A.java(实现类)
public class A implements IC{

    public String getName() {
        return "this is A speaking...";
    }
}
B.java(实现类)
public class B implements IC{

    public String getName() {
        return "this is B speaking...";
    }
   
}
IC.java(接口)
public interface IC {
   
    public String getName();

}
DataMaker.java(工厂)
public class DataMaker {
   
    public static IC getICName(String str){
        if(str.equals("A")){
            return new A();
        }else{
            return new B();
        }
    }
   
    public static void main(String[] args) {
        String str = "A";
        System.out.println(DataMaker.getICName(str).getName());;
    }
}
基本思路就是这样,不管实现类,而是在工厂里面统一处理。工厂的任务就是制造出成品。

以下是一个简单的俄罗斯方块游戏代码,注释在代码中: ```python import pygame import random # 初始化 pygame 模块 pygame.init() # 定义窗口大小 WINDOW_WIDTH = 400 WINDOW_HEIGHT = 500 # 定义方块大小 BLOCK_SIZE = 20 # 定义游戏区域大小 GAME_WIDTH = 10 * BLOCK_SIZE GAME_HEIGHT = 20 * BLOCK_SIZE # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # 创建窗口 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption("俄罗斯方块") # 创建字体对象 font = pygame.font.Font(None, 36) # 定义方块形状 SHAPES = [ [[1, 1, 1], [0, 1, 0]], [[0, 2, 2], [2, 2, 0]], [[3, 3, 0], [0, 3, 3]], [[4, 0, 0], [4, 4, 4]], [[0, 0, 5], [5, 5, 5]], [[6, 6], [6, 6]], [[7, 7, 7, 7]] ] # 定义方块颜色 COLORS = [ BLUE, YELLOW, GREEN, RED, WHITE, YELLOW, BLUE ] # 定义方块类型数量 SHAPE_COUNT = len(SHAPES) # 定义方块初始位置 INITIAL_POSITION = (GAME_WIDTH // 2 - BLOCK_SIZE * 2, 0) # 定义方块下落速度 FALL_SPEED = 500 # 定义方块移动速度 MOVE_SPEED = 100 # 定义方块旋转速度 ROTATE_SPEED = 100 # 定义游戏结束状态 GAME_OVER = False # 定义得分 score = 0 # 创建方块类 class Block: def __init__(self, shape, color, position): self.shape = shape self.color = color self.position = list(position) self.rotation = 0 # 绘制方块 def draw(self): for i in range(len(self.shape)): for j in range(len(self.shape[i])): if self.shape[i][j] != 0: pygame.draw.rect(window, self.color, (self.position[0] + j * BLOCK_SIZE, self.position[1] + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) # 移动方块 def move(self, direction): if direction == "left": self.position[0] -= BLOCK_SIZE elif direction == "right": self.position[0] += BLOCK_SIZE elif direction == "down": self.position[1] += BLOCK_SIZE # 旋转方块 def rotate(self): self.rotation = (self.rotation + 1) % len(self.shape) self.shape = list(zip(*self.shape[::-1])) # 判断方块是否超出边界 def is_out_of_bounds(self, direction): if direction == "left": return self.position[0] < 0 elif direction == "right": return self.position[0] + len(self.shape[0]) * BLOCK_SIZE > GAME_WIDTH elif direction == "down": return self.position[1] + len(self.shape) * BLOCK_SIZE > GAME_HEIGHT # 判断方块是否与其他方块重叠 def is_colliding(self, blocks): for block in blocks: for i in range(len(self.shape)): for j in range(len(self.shape[i])): if self.shape[i][j] != 0 and block.shape[i + self.position[1] // BLOCK_SIZE][j + self.position[0] // BLOCK_SIZE] != 0: return True return False # 创建方块工厂类 class BlockFactory: def __init__(self): self.blocks = [] # 创建新方块 def create_block(self): shape = SHAPES[random.randint(0, SHAPE_COUNT - 1)] color = COLORS[random.randint(0, SHAPE_COUNT - 1)] position = INITIAL_POSITION block = Block(shape, color, position) if block.is_colliding(self.blocks): global GAME_OVER GAME_OVER = True else: self.blocks.append(block) return block # 绘制所有方块 def draw_blocks(self): for block in self.blocks: block.draw() # 移动当前方块 def move_current_block(self, direction): current_block = self.blocks[-1] if not current_block.is_out_of_bounds(direction) and not current_block.is_colliding(self.blocks[:-1]): current_block.move(direction) # 旋转当前方块 def rotate_current_block(self): current_block = self.blocks[-1] if not current_block.is_colliding(self.blocks[:-1]): current_block.rotate() # 下落当前方块 def fall_current_block(self): current_block = self.blocks[-1] if not current_block.is_out_of_bounds("down") and not current_block.is_colliding(self.blocks[:-1]): current_block.move("down") else: self.create_block() # 判断是否有一行已经被填满 def check_full_rows(self): full_rows = [] for i in range(GAME_HEIGHT // BLOCK_SIZE): row_blocks = [block for block in self.blocks if block.position[1] == i * BLOCK_SIZE] if len(row_blocks) == GAME_WIDTH // BLOCK_SIZE: full_rows.append(i) return full_rows # 移除已经被填满的行 def remove_full_rows(self): full_rows = self.check_full_rows() if len(full_rows) > 0: for block in self.blocks[:]: if block.position[1] // BLOCK_SIZE in full_rows: self.blocks.remove(block) global score score += 10 elif block.position[1] // BLOCK_SIZE < min(full_rows): block.move("down") # 创建方块工厂对象 block_factory = BlockFactory() # 创建时钟对象 clock = pygame.time.Clock() # 游戏循环 while not GAME_OVER: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: GAME_OVER = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: block_factory.move_current_block("left") elif event.key == pygame.K_RIGHT: block_factory.move_current_block("right") elif event.key == pygame.K_DOWN: block_factory.fall_current_block() elif event.key == pygame.K_SPACE: block_factory.rotate_current_block() # 绘制背景 window.fill(BLACK) # 绘制游戏区域 pygame.draw.rect(window, WHITE, (0, 0, GAME_WIDTH, GAME_HEIGHT), 5) # 绘制所有方块 block_factory.draw_blocks() # 移除已经被填满的行 block_factory.remove_full_rows() # 绘制得分 score_text = font.render("Score: {}".format(score), True, WHITE) window.blit(score_text, (10, GAME_HEIGHT + 10)) # 更新屏幕 pygame.display.update() # 控制方块下落速度 if pygame.time.get_ticks() % FALL_SPEED == 0: block_factory.fall_current_block() # 控制方块移动速度 if pygame.time.get_ticks() % MOVE_SPEED == 0: keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: block_factory.move_current_block("left") elif keys[pygame.K_RIGHT]: block_factory.move_current_block("right") # 控制方块旋转速度 if pygame.time.get_ticks() % ROTATE_SPEED == 0: keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: block_factory.rotate_current_block() # 控制帧率 clock.tick(60) # 退出游戏 pygame.quit() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值