看了设计模式之美,记录一次看书心得
Posted mr.杰瑞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了看了设计模式之美,记录一次看书心得相关的知识,希望对你有一定的参考价值。
未优化的代码:
class IdGenerator
public static function insertLog()
return '记录日志';
public static function generate()
$id = "";
try
$hostName = '127.0.0.1';
$count = 0;
while ($count < 8)
$randomAscii = rand(1,122);
if ($randomAscii >= 48 && $randomAscii <= 57)
$randomChars[$count] = (string)chr($randomAscii);
$count++;
else if ($randomAscii >= 65 && $randomAscii <= 90)
$randomChars[$count] = (string)chr($randomAscii);
$count++;
else if ($randomAscii >= 97 && $randomAscii <= 122)
$randomChars[$count] = (string)chr($randomAscii);
$count++;
$id = printf("%s-%d-%s", $hostName,
time(), implode("",$randomChars));
catch (\\Exception $e)
self::insertLog();
throw $e;
return $id;
$id = (new IdGenerator)::generate();
var_dump($id);
- 目录设置是否合理、模块划分是否清晰、代码结构是否满足“高内聚、松耦合”? 是否遵循经典的设计原则和设计思想(SOLID、DRY、KISS、YAGNI、LOD等)? 设计模式是否应用得当?是否有过度设计?
- 代码是否容易扩展?如果要添加新功能,是否容易实现?
- 代码是否可以复用?是否可以复用已有的项目代码或类库?是否有重复造轮子?
- 代码是否容易测试?单元测试是否全面覆盖了各种正常和异常的情况?
- 代码是否易读?是否符合编码规范(比如命名和注释是否恰当、代码风格是否一致等)
优化后
<?php
interface IdGenerator
public function generate();
interface LogTraceIdGenerator extends IdGenerator
public function insertLog();
class RandomIdGenerator implements LogTraceIdGenerator
/**
* 日志
*/
public function insertLog()
// TODO: Implement insertLog() method.
/**
* @return int
* @throws Exception
*/
public function generate()
$substrOfHostName = $this->getLastfieldOfHostName();
$currentTimeMillis = time();
$randomString = $this->generateRandomAlphameric(8);
$id = printf("%s-%d-%s", $substrOfHostName, $currentTimeMillis, $randomString);
return $id;
/**
* @return String
*/
private function getLastfieldOfHostName()
$substrOfHostName = null;
try
$hostName = '127.0.0.1';
$substrOfHostName = $this->getLastSubstrSplittedByDot($hostName);
catch (\\Exception $e)
$this->insertLog();
throw $e;
return $substrOfHostName;
/**
* @param String $hostName
* @return String
*/
protected function getLastSubstrSplittedByDot(String $hostName)
//todo 这里是获取服务器地址逻辑
return $hostName;
/**
* 获取随机字符
* @param int $length
* @return string
*/
protected function generateRandomAlphameric(int $length)
while ($count < $length)
$maxAscii = 'z';
$randomAscii = rand(0, ord($maxAscii));
$isDigit= $randomAscii >= '0' && $randomAscii <= '9';
$isUppercase= $randomAscii >= 'A' && $randomAscii <= 'Z';
$isLowercase= $randomAscii >= 'a' && $randomAscii <= 'z';
if ($isDigit|| $isUppercase || $isLowercase)
$randomChars[$count] = (string) ($randomAscii);
++$count;
return implode('', $randomChars);
以上是关于看了设计模式之美,记录一次看书心得的主要内容,如果未能解决你的问题,请参考以下文章