图形(周长和面积)计算器
第一步:界面设计
图形(周长和面积)计算器
rect “>矩形 ||
三角形 ||
function __autoload($className){
include $className.’.class.php’;
}
echo new Form();
if($_POST[‘sub’]){
echo new Result();
}
?>
第二步:生成表单类
/*
* 表单类:
*
* 功能:根据不同的条件,输出不同样式的表单
*
* 核心思想:__toString()方法的使用
*
*/
class Form {
private $action;
private $shape;
function __construct($action=’index.php’){
$this->action=$action;
$this->shape=isset($_REQUEST[‘action’])?$_REQUEST[‘action’]:’rect’;
}
function __toString(){
$form='
’;return $form;
}
private function getRect(){
$input='请输入矩形的宽度和高度:
’;
$input.='shape.'”>’;
$input.=’长度:long ” value=”‘.$_POST[‘long’].'”>
’;
$input.=’宽度:
’;
return $input;
}
private function getTriangle(){
$input='请输入三角形的三条边:
’;
$input.='shape.'”>’;
$input.=’第一条边:
’;
$input.=’第二条边:
’;
$input.=’第三条边:
’;
return $input;
}
private function getCircle(){
$input='请输入圆形的半径:
’;
$input.='shape.'”>’;
$input.=’半径:
’;
return $input;
}
}
第三步:生成结果类
class Result {
private $shape;
function __construct(){
switch ($_POST[‘action’]) {
case ‘rect’:
$this->shape=new Rect();
break;
case ‘triangle’:
$this->shape=new Triangle();
break;
case ‘circle’:
$this->shape=new Circle();
break;
default:
$this->shape=false;
break;
}
}
function __toString(){
if($this->shape){
$result=$this->shape->shapeName.’的周长为:’.$this->shape->C().’;面积为:’.$this->shape->S();
return $result;
}else {
return ‘没有这个形状’;
}
}
}
第四步:生成抽象类——定义功能模块开发规范
abstract class Shape {
var $shapeName;
abstract function S();
abstract function C();
protected function validate($value,$ message ){
if ($value==” || !is_numeric($value) || $value < 0) {
echo ‘’.$message.’必须为非负数且不能为空!’;
return false;
}else {
return true;
}
}
}
第五步:定义各个图像类
1. 矩形类
class Rect extends Shape{
private $width;
private $long;
function __construct(){
$this->shapeName=’矩形’;
if($this->validate($_POST[‘width’], ‘矩形的宽’) && $this->validate($_POST[‘long’], ‘矩形的长’)){
$this->width=$_POST[‘width’];
$this->long=$_POST[‘long’];
}else{
exit();
}
}
function C(){
$C=($this->long+$this->width)*2;
return $C;
}
function S(){
$S=$this->long*$this->width;
return $S;
}
}
2. 三角形类
class Triangle extends Shape{
private $a;
private $b;
private $c;
function __construct(){
$this->shapeName=’三角形’;
if($this->check()){
$this->a=$_POST[‘side1’];
$this->b=$_POST[‘side2’];
$this->c=$_POST[‘side3’];
}else {
exit();
}
}
function C(){
$C=$this->a+$this->b+$this->c;
return $C;
}
function S(){//利用”海伦公式”
$p=($this->a+$this->b+$this->c)/2;
$S=sqrt($p*($p-$this->a)*($p-$this->b)*($p-$this->c));
return $S;
}
private function check(){
//两边之和大于第三边
//两边之差大于第三边
}
}
3. 圆形类
class Circle extends Shape{
private $r;
function __construct(){
$this->shapeName=’圆形’;
if ($this->validate($_POST[‘radius’], ‘圆的半径’)) {
$this->r=$_POST[‘radius’];
}else {
exit();
}
}
function C(){
$C=2*round( pi (),0)*$this->r;
return $C;
}
function S(){
$S=round(pi(),0)*pow($this->r, 2);
return $S;
}
}
相关文章
本站已关闭游客评论,请登录或者注册后再评论吧~