首页 \ 问答 \ 在课堂上使用特征,为什么?(Using traits over classes, why?)

在课堂上使用特征,为什么?(Using traits over classes, why?)

这是课程的方式吗?

Class Main 
{
    $this->a = new A();
    $this->b = new B();
    $this->c = new C();

    $this->b->doTranslate($this->a->saySomething());
}

这就是特质如何做到的,不是吗?

Class Main {
    use A;
    use B;
    use C;

    $this->doTranslate($this->saySomething());
}

我根本没有太多关于特征的知识,但是通过查看新的PHP 5.4特征示例,它们似乎只对单个案例有帮助。 A class only be extended once to use $this together, but we can use multiple traits.

问题1:使用特征而不是基本类是否是唯一的优势?

问题2:如果trait A, B, and C都有一个名为example()的函数,当我尝试$this->example(); PHP将如何确定将使用哪种特性? 会发生什么事?

另外,不要写一面文字; 只是给我一个简短的代码示例,简短的简介,我可以看看和承担。 我不熟悉特质,也不知道它们到底是什么。


This is how classes do it?

Class Main 
{
    $this->a = new A();
    $this->b = new B();
    $this->c = new C();

    $this->b->doTranslate($this->a->saySomething());
}

And this is how traits do it, not?

Class Main {
    use A;
    use B;
    use C;

    $this->doTranslate($this->saySomething());
}

I don't have much knowledge about traits at all, but by looking at new PHP 5.4 trait examples, they only seem to help in a single case. A class only be extended once to use $this together, but we can use multiple traits.

Question 1: Is it the only advantage of using traits over basic classes?

Question 2: If trait A, B, and C all have a function named example(), when I try $this->example(); how PHP is going to determine which trait will be used? What's going to happen?

Additionally, instead of writing a wall of text; just provive me a short code example with a short brief that I can have a look and undertstand. I'm not familiar with traits and don't know what they truly are.


原文:https://stackoverflow.com/questions/15164600
更新时间:2021-12-12 20:12

最满意答案

我知道你想要非阻塞的NIO,但如果你想要一个高性能的NIO服务器,我会从这个开始作为一个基线,如果没有其他原因而不是简单。 通常最简单的也是最快的。

package example.nio;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NioEchoServer implements Runnable, Closeable {
    private final ExecutorService service = Executors.newCachedThreadPool();
    private final ServerSocketChannel ssc;
    private volatile boolean closed = false;

    public NioEchoServer(int port) throws IOException {
        ssc = ServerSocketChannel.open();
        ssc.socket().setReuseAddress(true);
        ssc.bind(new InetSocketAddress(port));
        service.submit(this);
    }

    @Override
    public void run() {
        try {
            while (!closed) {
                SocketChannel sc = ssc.accept();
                service.submit(new EchoHandler(sc));
            }
        } catch (IOException e) {
            if (!closed)
                e.printStackTrace();
        } finally {
            closeQuietly(ssc);
        }
    }

    @Override
    public void close() throws IOException {
        closed = true;
        service.shutdownNow();
        closeQuietly(ssc);
    }

    static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) closeable.close();
        } catch (IOException ignored) {
        }
    }

    public int getPort() {
        return ssc.socket().getLocalPort();
    }

    static class EchoHandler implements Runnable {
        private final SocketChannel sc;

        public EchoHandler(SocketChannel sc) {
            this.sc = sc;
        }

        @Override
        public void run() {
            ByteBuffer bb = ByteBuffer.allocateDirect(64 * 1024);
            try {
                while (!Thread.interrupted() && sc.read(bb) > 0) {
                    int len = bb.position();
                    bb.flip();
                    while (bb.remaining() > 0)
                       sc.write(bb);
                    // write everything a second time.
                    bb.position(0);
                    bb.limit(len);
                    while (bb.remaining() > 0)
                        sc.write(bb);

                    bb.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("Server disconnected");
                closeQuietly(sc);
            }
        }
    }
}

package example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;

public class NioEchoClient {
    public static void main(String... arg) throws IOException, InterruptedException {
        NioEchoServer nes = new NioEchoServer(0); // use a free port.
        final SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", nes.getPort()));
        // send data for 2 seconds.
        long writeCount = 0;
        final AtomicLong readCount = new AtomicLong();
        long start = System.currentTimeMillis();
        long end = start + 2000;
        Thread reader = new Thread(new Runnable() {
            @Override
            public void run() {
                ByteBuffer bb = ByteBuffer.allocateDirect(64 * 1024);
                bb.clear();
                int read;
                try {
                    while ((read = sc.read(bb)) > 0) {
                        bb.clear();
                        readCount.addAndGet(read);
                    }
                } catch (IOException ignored) {
                }
            }
        });
        reader.start();
        ByteBuffer bb = ByteBuffer.allocateDirect(64 * 1024);
        while (end > System.currentTimeMillis()) {
            bb.clear();
            int write = sc.write(bb);
            if (write < 0)
                throw new AssertionError("Unexpected disconnection?");
            writeCount += write;
        }
        sc.shutdownOutput();
        reader.join();
        long time = System.currentTimeMillis() - start;
        System.out.printf("Wrote: %,d bytes and read: %,d bytes in %,d ms%n",
                writeCount, readCount.get(), time);
        sc.close();
        nes.close();
    }
}

版画

Wrote: 186,318,848 bytes and read: 186,318,848 bytes in 2,001 ms

当我写的两倍于我读的时候

Wrote: 118,161,408 bytes and read: 236,322,816 bytes in 2,002 ms

I know you want non-blocking NIO, but if you want a performant NIO server I would start with this as a base line if for no other reason than simplicity. Often the simplest is also the fastest.

package example.nio;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NioEchoServer implements Runnable, Closeable {
    private final ExecutorService service = Executors.newCachedThreadPool();
    private final ServerSocketChannel ssc;
    private volatile boolean closed = false;

    public NioEchoServer(int port) throws IOException {
        ssc = ServerSocketChannel.open();
        ssc.socket().setReuseAddress(true);
        ssc.bind(new InetSocketAddress(port));
        service.submit(this);
    }

    @Override
    public void run() {
        try {
            while (!closed) {
                SocketChannel sc = ssc.accept();
                service.submit(new EchoHandler(sc));
            }
        } catch (IOException e) {
            if (!closed)
                e.printStackTrace();
        } finally {
            closeQuietly(ssc);
        }
    }

    @Override
    public void close() throws IOException {
        closed = true;
        service.shutdownNow();
        closeQuietly(ssc);
    }

    static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) closeable.close();
        } catch (IOException ignored) {
        }
    }

    public int getPort() {
        return ssc.socket().getLocalPort();
    }

    static class EchoHandler implements Runnable {
        private final SocketChannel sc;

        public EchoHandler(SocketChannel sc) {
            this.sc = sc;
        }

        @Override
        public void run() {
            ByteBuffer bb = ByteBuffer.allocateDirect(64 * 1024);
            try {
                while (!Thread.interrupted() && sc.read(bb) > 0) {
                    int len = bb.position();
                    bb.flip();
                    while (bb.remaining() > 0)
                       sc.write(bb);
                    // write everything a second time.
                    bb.position(0);
                    bb.limit(len);
                    while (bb.remaining() > 0)
                        sc.write(bb);

                    bb.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("Server disconnected");
                closeQuietly(sc);
            }
        }
    }
}

package example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;

public class NioEchoClient {
    public static void main(String... arg) throws IOException, InterruptedException {
        NioEchoServer nes = new NioEchoServer(0); // use a free port.
        final SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", nes.getPort()));
        // send data for 2 seconds.
        long writeCount = 0;
        final AtomicLong readCount = new AtomicLong();
        long start = System.currentTimeMillis();
        long end = start + 2000;
        Thread reader = new Thread(new Runnable() {
            @Override
            public void run() {
                ByteBuffer bb = ByteBuffer.allocateDirect(64 * 1024);
                bb.clear();
                int read;
                try {
                    while ((read = sc.read(bb)) > 0) {
                        bb.clear();
                        readCount.addAndGet(read);
                    }
                } catch (IOException ignored) {
                }
            }
        });
        reader.start();
        ByteBuffer bb = ByteBuffer.allocateDirect(64 * 1024);
        while (end > System.currentTimeMillis()) {
            bb.clear();
            int write = sc.write(bb);
            if (write < 0)
                throw new AssertionError("Unexpected disconnection?");
            writeCount += write;
        }
        sc.shutdownOutput();
        reader.join();
        long time = System.currentTimeMillis() - start;
        System.out.printf("Wrote: %,d bytes and read: %,d bytes in %,d ms%n",
                writeCount, readCount.get(), time);
        sc.close();
        nes.close();
    }
}

prints

Wrote: 186,318,848 bytes and read: 186,318,848 bytes in 2,001 ms

when I write twice as much as I read I get

Wrote: 118,161,408 bytes and read: 236,322,816 bytes in 2,002 ms

相关问答

更多
  • Gcc是正确的。 std::stringstream继承自std::basic_ostream ,并且根据operator<<(std::basic_ostream) (从ss << "foo"; )调用的operator<<(std::basic_ostream)的行为, 效果:表现得像格式化的插件(如[ostream.formatted.reqmts]中所述)。 从§30.7.5.2.1/ 1通用要求[ostream.formatted.reqmts] : (强调我的) 每个格式化的输出函数都是通过构造 ...
  • 我找不到问题。 但是当我使用DB_BTREE而不是DB_RECNO时,它工作得很完美。 I couldn't find the problem. But when i'm using DB_BTREE instead of DB_RECNO, it working perfect.
  • 使用范围对象中的单元格方法来引用另一个工作表需要您首先激活该工作表(请参阅msdn中的第5节) Sub ReferToCells() Dim arrData() As Variant, i As Long Sheets("Sheet2").Activate arrData = Range(Cells(1, 1), Cells(2, 1)).Value For i = 1 To UBound(arrData) Debug.Print arrData(i, 1) ...
  • 我不知道是否有SDK方法可以做到这一点,但Linux将允许您列出进程/打开文件/套接字,你可以尝试从那里抓取东西。 首先使用ps命令获取进程的PID,输入: $ ps -aef | grep {process-name} $ ps -aef | grep httpd 接下来将此PID传递给pfiles命令, $ pfiles {PID} $ pfile 3533 这就是你如何列出firefox使用的所有打开文件... lsof -p `ps -C firefox -o pid=` 您可以使用Syste ...
  • 所以你正在写一个文件流,然后将文件读回流? 您是否需要编写文件然后对其进行处理,或者您是否可以直接使用源流? 如果你需要这个文件,我会使用一个循环来持续检查文件是否每秒都存在直到它出现(或者经过了一段时间) - 如果你不能写文件,编写器会给你一个错误,所以你知道它最终会出现。 So you are writing a stream to a file, then reading the file back to a stream? Do you need to write the file then pos ...
  • 无需定义自己的功能来读取和写入内部EEPROM中的数据。 AVR为此提供了库。 以下是示例代码: - #define F_CPU 16000000UL #include #include #include int main(void) { char read[5]; eeprom_write_byte (0, '0'); eeprom_write_byte (1, '1'); eeprom_ ...
  • 弄清楚了。 我将键值误解为您要保存到存储的整数,而不是值存储在存储位置的实际键值。 因此,每次我保存并检索它所保存的值并根据当时的值从不同位置检索。 查看下一页的Persist Counter代码示例帮助我https://developer.pebble.com/examples/ 相关代码现在 #define NUM_TOTAL_DEFAULT 0 #define NUM_TARGETS_DEFAULT 0 #define NUM_TOTAL_PKEY 1 #define NUM_TARGETS_PKEY ...
  • 请注意,您可以简单地使用Files.copy(Paths.get(inFileStr),Paths.get(outFileStr), StandardCopyOption.REPLACE_EXISTING)来复制文件,就像您的示例代码一样,可能更快,并且只有一行代码。 否则,如果您已经打开了两个文件通道,则可以使用 in.transferTo(0, in.size(), out)将in通道的全部内容传送到out通道。 请注意,此方法允许指定源文件中将传输到目标通道的当前位置(最初为零)的范围,并且还有一种方 ...
  • 我知道你想要非阻塞的NIO,但如果你想要一个高性能的NIO服务器,我会从这个开始作为一个基线,如果没有其他原因而不是简单。 通常最简单的也是最快的。 package example.nio; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChann ...
  • 以下语句为循环的每次迭代抛出异常: energyCurrent = (int) childSnap.child("Character").child("energyCurrent").getValue(); 数字字符串上的getValue()返回一个Long ,它不能取消装箱到int ,而是抛出: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer catch-block中的continue语句 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)