抽象工厂设计模式-创建型设计模式 [PHP]

抽象工厂:\n在不指定具体类的情况下创建一系列相关或从属对象。最重要的特征就是抽象类的组合.\n通常,创建的类都实现相同的接口。抽象工厂的客户端并不关心这些对象的创建方式,只是知道它们如何组合在一起。

三个抽象类

 

interface WriterFactory{\n    public function createCsvWriter(): CsvWriter;\n    public function createJsonWriter(): JsonWriter;\n}\ninterface CsvWriter{\n    public function write(array $line): string;\n}\ninterface JsonWriter{\n    public function write(array $data, bool $formatted): string;\n}

分为linux下和win下的六个具体实现类:\nUnixWriterFactory WinWriterFactory 这俩就是传说中的抽象工厂, 生成下面的抽象类的具体实例\nUnixCsvWriter WinCsvWriter\nUnixJsonWriter WinJsonWriter

具体使用:

具体使用:\nclass AbstractFactoryTest extends TestCase{\n    //提供工厂,提供了两个系统下的工厂\n    public function provideFactory()\n    {\n        return [\n            [new UnixWriterFactory()],\n            [new WinWriterFactory()]\n        ];\n    }\n    //使用提供的工厂,创建对象,当我们在定义参数类型时都可以直接使用抽象类的名字来定义\n    public function testCanCreateCsvWriterOnUnix(WriterFactory $writerFactory)\n    {\n        $this->assertInstanceOf(JsonWriter::class, $writerFactory->createJsonWriter());\n        $this->assertInstanceOf(CsvWriter::class, $writerFactory->createCsvWriter());\n    }\n}

Android App端与PHP Web端的简单数据交互实现示例

需要实现Android App端与PHP Web端的简单数据交互的实现,当前场景是Web端使用的是MySql数据库,Apache服务器和PHP语言编写的。数据交互的简单理解就是Android能向服务端进行数据获取,同时也能进行数据提交。

实现流程

流程说明

  1. Andorid Server端对MySql数据库进行简单的查询操作,并将查询数据结果转换为Json格式提供给Andorid利用OKhttp读取再解析Json展示到APP上;同时Andorid端利用OKhttp提交给Andorid Server端,由Server端对MySql数据库对提交数据的添加。
  2. Apache Server端通过解析PHP源代码,对MySql数据库的增删查改显示在WebSite。

具体实现

Andorid Server

获取数据

get_all_found_items.php

<?php \nheader(\'Content-Type:text/html;charset=utf-8\');/*设置php编码为utf-8*/\n/* \n * Following code will list all the items \n */ \n  \n// array for JSON response \n$response = array(); \n  \n// include db connect class \nrequire_once __DIR__ . \'/db_connect.php\'; \n  \n// connecting to db \n$db = new DB_CONNECT(); \n  \n// get all items from items table \n$result = mysql_query(\"SELECT *FROM items WHERE type=\'1\'\") or die(mysql_error()); \n// check for empty result \nif (mysql_num_rows($result)   0) { \n  // looping through all results \n  // items node \n  $response[\"items\"] = array(); \n  \n  while ($row = mysql_fetch_array($result)) { \n    // temp user array \n    $items = array(); \n    $items[\"what\"] = $row[\"what\"]; \n    $items[\"when\"] = $row[\"when\"]; \n    $items[\"where\"] = $row[\"where\"]; \n    $items[\"detail\"] = $row[\"detail\"];\n    $items[\"posttime\"] = $row[\"posttime\"];  \n $resultcontcat = mysql_query(\"SELECT *FROM guests\") or die(mysql_error()); \n while ($row1 = mysql_fetch_array($resultcontcat)) { \n  if ($row1[\"id\"] == $row[\"gid\"]){\n  $items[\"contact\"] = $row1[\"contact\"];\n  }\n  }\n    // push single items into final response array \n    array_push($response[\"items\"], $items); \n  } \n  // success \n  $response[\"success\"] = 1; \n  \n  // echoing JSON response \n  echo json_encode($response,JSON_UNESCAPED_UNICODE); \n} else { \n  // no items found \n  $response[\"success\"] = 0; \n  $response[\"message\"] = \"No items found\"; \n  \n  // echo JSON \n  echo json_encode($response,JSON_UNESCAPED_UNICODE); \n} \n? 

如以上PHP代码可知通过require_once()函数包含db_connect.php文件,执行数据库配置文件。定义数组$response接收查询的数据结果,通过判断不同的情况赋值$response[“success”],并返回到Web页面显示

PHP文件执行结果JSON

 {\n  \"items\": [\n    {\n      \"what\": \"手表\",\n      \"when\": \"2017-10-21 00:00:00\",\n      \"where\": \"北区宿舍楼#504\",\n      \"detail\": \"白色的手表,XX品牌\",\n      \"posttime\": \"2017-10-21 13:03:09\",\n      \"contact\": \"138123456\"\n    },\n    {\n      \"what\": \"手机\",\n      \"when\": \"2017-10-04 00:00:00\",\n      \"where\": \"北区商店#111\",\n      \"detail\": \"iphone6s,土豪金\",\n      \"posttime\": \"2017-10-21 13:03:46\",\n      \"contact\": \"137123456\"\n    },\n    {\n      \"what\": \"电脑\",\n      \"when\": \"2017-10-21 14:39:54\",\n      \"where\": \"图书馆#203\",\n      \"detail\": \"联想品牌笔记本\",\n      \"posttime\": \"2017-10-21 17:08:14\",\n      \"contact\": \"5670001\"\n    },\n    {\n      \"what\": \"细说PHP\",\n      \"when\": \"2017-09-21 13:03:46\",\n      \"where\": \"南馆#403\",\n      \"detail\": \"黑色封面,第二版《细说PHP》\",\n      \"posttime\": \"2017-10-21 17:36:53\",\n      \"contact\": \"63513641\"\n    }\n  ],\n  \"success\": 1\n}

提交数据

create_found_items.php

<?php \nheader(\'Content-Type:text/html;charset=utf-8\');/*设置php编码为utf-8*/  \n/* \n * Following code will create a new product row \n * All product details are read from HTTP GET Request \n */ \n  \n// array for JSON response \n$response = array(); \n  \n// check for required fields \nif (isset($_GET[\'what\']) && isset($_GET[\'when\']) && isset($_GET[\'where\']) && isset($_GET[\'detail\'])&& isset($_GET[\'contact\'])) { \n  \n  $what = $_GET[\'what\']; \n  $when = $_GET[\'when\']; \n  $where = $_GET[\'where\']; \n  $detail = $_GET[\'detail\']; \n  $contact = $_GET[\'contact\']; \n \n  // include db connect class \n  require_once __DIR__ . \'/db_connect.php\'; \n  \n  // connecting to db \n  $db = new DB_CONNECT(); \n  \n  // mysql inserting a new row \n $result2 = mysql_query(\"INSERT INTO guests(contact) VALUES(\'$contact\')\"); \n $gidresult = mysql_query(\"SELECT id FROM guests WHERE contact=\'$contact\'\"); \n while ($row = mysql_fetch_array($gidresult)) { \n $gid=$row[\'id\'];\n }\n $result1 = mysql_query(\"INSERT INTO items(what, when, where, type ,gid, detail) VALUES(\'$what\', \'$when\', \'$where\', \'1\', \'$gid\', \'$detail\')\"); \n \n // check if row inserted or not \n if ($result1 && $result2) { \n // successfully inserted into database \n $response[\"success\"] = 1; \n $response[\"message\"] = \"Items successfully created.\"; \n \n // echoing JSON response \n echo json_encode($response,JSON_UNESCAPED_UNICODE); \n } else { \n // failed to insert row \n $response[\"success\"] = 0; \n $response[\"message\"] = \"Oops! An error occurred.\"; \n \n // echoing JSON response \n echo json_encode($response,JSON_UNESCAPED_UNICODE); \n } \n} else { \n // required field is missing \n $response[\"success\"] = 0; \n $response[\"message\"] = \"Required field(s) is missing\"; \n \n // echoing JSON response \n echo json_encode($response,JSON_UNESCAPED_UNICODE); \n} \n? 

判断GET请求的参数是否都存在,把获取的GET请求参数作为数据INSERT TO MySQL数据库。判断INSERT执行过程赋值$response[“success”]对应相应的$response[“message”],显示在Web页面。

Andorid

获取数据核心代码 queryLosts()函数

private void queryLosts() {\n losts.clear();\n new Thread(new Runnable() {\n \n @Override\n public void run() {\n  // TODO Auto-generated method stub\n  \n     OkHttpClient okHttpClient = new OkHttpClient();\n     String url = \"http://webSite/androidapi/get_all_lost_items.php\";\n     Request request = new Request.Builder()\n         .url(url)\n         .build();\n     Call call = okHttpClient.newCall(request);\n     try {\n       Response response = call.execute();\n       String res = response.body().string();\n       if (res != null && !res.trim().equals(\"\")){\n         JSONObject jsonObject = new JSONObject(res);\n         if (jsonObject.getInt(\"success\") == 1){\n           JSONArray jsonArray = jsonObject.getJSONArray(\"items\");\n           for (int i = jsonArray.length() - 1;i  = 0;i--){\n             JSONObject item = jsonArray.getJSONObject(i);\n             String what = null;\n             try {\n               what = item.getString(\"what\");\n             }catch (Exception e){\n             }\n             String when = null;\n             try{\n               when = item.getString(\"when\");\n             }catch (Exception e){\n             }\n             String where = null;\n             try{\n               where = item.getString(\"where\");\n             }catch (Exception e){\n             }\n             String detail = null;\n             try {\n               detail = item.getString(\"detail\");\n             }catch (Exception e){\n             }\n             String contact = null;\n             try {\n               contact = item.getString(\"contact\");\n             }catch (Exception e){\n             }\n             Lost lost = new Lost();\n             lost.setTitle(what);\n             String des = \"地点:\" + (where == null?\"\":where) +\"   \"+\"时间:\" + (when == null?\"\":when)+\"r\" + \"   \"+\"描述:\" + (detail == null?\"\":detail);\n             lost.setDescribe(des);\n             lost.setPhone(contact == null?\"\":contact);\n             losts.add(lost);\n           }\n         }\n       }\n     } catch (Exception e) {\n       e.printStackTrace();\n       showErrorView(0);\n     }\n     if (losts == null || losts.size() == 0) {\n     handler.sendEmptyMessage(1);\n       return;\n     }\n     if (losts.size()   0){\n      handler.sendEmptyMessage(2);\n     }\n }\n }).start();

利用Android网络框架OKhttp,OKhttp一个处理网络请求的开源项目,是安卓端最火热的轻量级框架.请求接口url地址,获取Json数据利用JSONObject对Json数据进行解析。

提交数据核心代码 addLost()函数

public Handler handler = new Handler(){\n public void handleMessage(android.os.Message msg) {\n switch(msg.what){\n  case 1:\n  Toast.makeText(this,\"提交成功\",Toast.LENGTH_LONG).show();\n  break;\n  case 2:\n  Toast.makeText(this,\"提交失败\",Toast.LENGTH_LONG).show();\n  break;\n }\n }\n};\nprivate void addLost(){\n OkHttpClient okHttpClient = new OkHttpClient();\n String url =\"http://website/androidapi/create_lost_items.php?what=\"+title+\"&when=\"+time+\"&where=\"+place+\"&detail=\"+describe+\"&contact=\"+photo+\"\";\n Request request = new Request.Builder()\n  .url(url)\n  .build();\n \n try{\n Response response = okHttpClient.newCall(request).execute();\n res = response.body().string();\n handler.sendEmptyMessage(1);\n }catch (Exception e)\n {\n e.printStackTrace();\n handler.sendEmptyMessage(2);\n }\n}

同样利用Okhttp,GET方式提交参数,try-catch获取异常,通过返回值给出一定的提交结果提示。

生成器模式-创建型设计模式 [PHP]

目的:生成器的目的是将复杂对象的创建过程(流程)进行抽象,生成器表现为接口的形式。

如果对象有复杂的继承树,理论上创建对象的生成器也同样具有复杂的继承树。

传进来一个生成器, 我调用这个生成器来生成我所需要的汽车,这就是生成器模式的核心.这个生成器Builder是个接口,把复杂对象的创建过程进行抽象

class Director\n{\n    public function build(Builder $builder): Vehicle\n    {\n        $builder->createVehicle();\n        $builder->addDoors();\n        $builder->addEngine();\n        $builder->addWheel();\n        return $builder->getVehicle();\n    }\n}

这就是生成器这个接口

 

interface Builder\n{\n    public function createVehicle();\n    public function addWheel();\n    public function addEngine();\n    public function addDoors();\n    public function getVehicle(): Vehicle;\n}

有两个具体的实现类 CarBuilder TruckBuilder 分别生成汽车和卡车

 

class TruckBuilder implements Builder\n{\n    private Truck $truck;\n    public function addDoors(){\n    }\n    public function addEngine(){\n    }\n    public function addWheel(){\n    }\n\n    public function createVehicle(){\n    }\n\n    public function getVehicle(): Vehicle{\n    }\n}

使用的时候,先创建builder,把builder通过参数传递进去

$truckBuilder = new TruckBuilder();\n$newVehicle = (new Director())->build($truckBuilder);